C# 构造函数中的泛型类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/700966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:01:01  来源:igfitidea点击:

Generic Type in constructor

c#.netgenericsinversion-of-control

提问by CSharpAtl

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)
{}

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?

我希望创建此对象的代码指定 IGenericType(使用控制反转)。我还没有看到发生这种情况的方法。有什么建议可以实现这一点吗?

I want someone to create the object like:

我希望有人创建这样的对象:

Constructor varname = new Constructor(1, new GenericType<int>());

采纳答案by Jon Skeet

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.

如果需要,然后在构造函数之后执行任何您需要的操作。在某些情况下,另一种选择可能是引入一个由通用接口扩展的非通用接口。

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