在构造泛型类型 [英] Generic Type in constructor

查看:133
本文介绍了在构造泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类型接口,并希望对象的构造采取的通用接口

类似:

 公共构造函数(INT胡说,IGenericType< T>实例)
{}

我要创建该对象指定IGenericType(控制使用反转)的代码。我还没有看到这种情况发生的方法。任何建议,以实现这一目标。



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

 构造VARNAME =新的构造函数(1,新GenericType< INT>()); 


解决方案

您不能使构造通用的,但你可以使用一个通用的静态方法来代替:

 公共静态构造函数的CreateInstance< T>(INT胡说,IGenericType< T>实例)

,然后做任何你需要的构造后,如果需要的话。 。在某些情况下,另一种方法是引入该通用接口延伸的非通用接口



编辑:由于每注释...



如果您想要保存的参数到新创建的对象,你想在一个强类型的方式做的话,那么类型必须是通用的为好。



在这一点上构造问题消失,但你的可能的希望在非泛型类型反正保留静态泛型方法:让您可以充分利用类型推断

 公共静态类Foo 
{
公共静态美孚< T>的CreateInstance(IGenericType< T>实例)
{
返回新的Foo< T>(实例);
}
}

公共类Foo< T>
{
公共美孚(IGenericType< T>实例)
{
//无论
}
}

..

IGenericType<串GT; X =新GenericType<串GT;();
&符LT;字符串> noInference =新的Foo<串GT;(x)的;
&符LT;字符串> withInference = Foo.CreateInstance(X);


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?

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.

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<T> CreateInstance(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);

这篇关于在构造泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆