我有一个通用类型接口并且想要一个对象的构造函数来接收通用接口.喜欢:
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<T> instance) {}我希望创建此对象的代码指定 IGenericType(使用控制反转).我还没有看到发生这种情况的方法.有什么建议可以实现这一点吗?
I want the code that creates this object to specify the IGenericType (use Inversion of Control). I have not seen a way for this to happen. Any suggestions to accomplish this?
我希望有人像这样创建对象:
I want someone to create the object like:
Constructor varname = new Constructor(1, new GenericType<int>()); 推荐答案您不能使构造函数泛型,但可以改用泛型静态方法:
You can't make constructors generic, but you can use a generic static method instead:
public static Constructor CreateInstance<T>(int blah, IGenericType<T> 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.
根据评论...
如果要将参数保存到新创建的对象中,并且希望以强类型方式进行,那么该类型也必须是泛型的.
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<T> CreateInstance<T>(IGenericType<T> instance) { return new Foo<T>(instance); } } public class Foo<T> { public Foo(IGenericType<T> instance) { // Whatever } } ... IGenericType<string> x = new GenericType<string>(); Foo<string> noInference = new Foo<string>(x); Foo<string> withInference = Foo.CreateInstance(x);更多推荐
构造函数中的泛型类型
发布评论