C # generic factory method

Maybe this is a simple question for newbies in C #, but the way it is --- it will be a new break in my other questions, which are so difficult that no one knows the answer to them. :)

Say I have a generic type in C #:

Thing<T>

And let me say that I want to do something using the static factory method. In Java, this is not a problem:

public static <T> Thing<T> createThing()
{
  return flag ? new Thing<Integer>(5) : new Thing<String>("hello");
}

How to do it in C #? Thank.

+3
source share
3 answers

If you want to return an instance of a template template using one of many different template arguments, one way to do this is with an abstract base (or interface):

abstract class UntypedThing { }
class Thing<T> : UntypedThing
{
    public Thing(T t) { }
}

class Foo
{
    public static UntypedThing createThing(bool flag)
    {
        if (flag)
            return new Thing<int>(5);
        else return new Thing<String>("hello");
    }
}

UntypedThing , . Thing , . factory Foo .

+4

, , - .

public class ThingFactory  {
    public object Create(bool flag) {
        Type outputType = null;
        if(flag) {
            outputType = typeof(string);
        } else {
            outputType = typeof(int);
        }
        return Activator.CreateInstance(typeof(Thing<>).MakeGenericType(outputType));
    }
}

, , , , , Create.

. .

+3

, , , - .

, # 4 ​​. -, Thing "out" :

public interface Thing<out T> {...}

- , # . , T :

public interface Thing<out T>
{
  public T GetT();

Thing, ?

Thing<object> thing=createThing();

, .

, , factory :

public static Thing<object> createThing() {...}

, , ?

IList<Thing<object>> list=new List<Thing<object>>();
Thing<object> thing=createThing();
list.Add(thing);

, , Thing T Object, # .

Java, :

public class Thing<T> {...}

public static <T> Thing<T> createThing() {...}

List<?> things=new ArrayList<Thing<?>>();
Thing<?> thing=createThing();
things.add(thing);

, , T , :

public static <T extends MyBaseType> Thing<T> createThing() {...}

List<? extends MyBaseType> things=new ArrayList<Thing<? extends MyBaseType>>();
Thing<? extends MyBaseType> thing=createThing();
things.add(thing);

, T , .

, , # #. ( , .)

? , , , .

(, getValue(), T getValue()? Ack, --- .)

0

Source: https://habr.com/ru/post/1765727/


All Articles