构造函数中的泛型类型

编程入门 行业动态 更新时间:2024-10-25 18:32:14
本文介绍了构造函数中的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个通用类型接口并且想要一个对象的构造函数来接收通用接口.喜欢:

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);

更多推荐

构造函数中的泛型类型

本文发布于:2023-11-02 15:07:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552720.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!