Generic Type in constructor

后端 未结 1 1219
青春惊慌失措
青春惊慌失措 2020-11-27 18:40

I have a Generic Type Interface and want a constructor of an object to take in the Generic Interface.
Like:

public Constructor(int blah, IGenericType<         


        
1条回答
  •  时光取名叫无心
    2020-11-27 18:56

    You can't make constructors generic, but you can use a generic static method instead:

    public static Constructor CreateInstance(int blah, IGenericType instance)
    

    and then do whatever you need to after the constructor, if required. Another alternative in some cases might be to introduce a non-generic interface which the generic interface extends.

    EDIT: As per the comments...

    If you want to save the argument into the newly created object, and you want to do so in a strongly typed way, then the type must be generic as well.

    At that point the constructor problem goes away, but you may want to keep a static generic method anyway in a non-generic type: so you can take advantage of type inference:

    public static class Foo
    {
        public static Foo CreateInstance(IGenericType instance)
        {
            return new Foo(instance);
        }
    }
    
    public class Foo
    {
        public Foo(IGenericType instance)
        {
            // Whatever
        }
    }
    
    ...
    
    IGenericType x = new GenericType();
    Foo noInference = new Foo(x);
    Foo withInference = Foo.CreateInstance(x);
    

    0 讨论(0)
提交回复
热议问题