在C#泛型 - 我怎么可以创建一个变量类型与参数的实例? [英] Generics in C# - how can I create an instance of a variable type with an argument?

查看:158
本文介绍了在C#泛型 - 我怎么可以创建一个变量类型与参数的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类,在这里我想实例化泛型类型的对象。我想使用该类型的构造函数的参数。

我的code:

 公共类GenericClass< T>其中T:Some_Base_Class,新的()
{
    公共静态ŧSomeFunction(字符串s)
    {
        如果(String.IsNullOrEmpty(多个))
            返回新的T(some_param);
    }
}

我得到了一个错误

 新T(some_param)


  

'T':无法创建变量的实例时提供的参数
  键入


任何想法我怎么能这样做呢?


解决方案

在看看<一个href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\"><$c$c>Activator.CreateInstance.例如:

  VAR实例= Activator.CreateInstance(typeof运算(T),新的对象[] {NULL,NULL});

显然与该类型的构造函数之一有望适当的值替换秒。

如果您收到有关编译器错误不能转换对象类型T ,然后包括为T

  VAR实例= Activator.CreateInstance(typeof运算(T)
                  新的对象[] {NULL,NULL})为T;

I've got a generics class, where I want to instantiate an object with the generic type. I want to use an argument for the constructor of the type.

My code:

public class GenericClass<T> where T : Some_Base_Class, new()
{
    public static T SomeFunction(string s)
    {
        if (String.IsNullOrEmpty(s))
            return new T(some_param);
    }
}

I get an error on the

new T(some_param)

'T': cannot provide arguments when creating an instance of a variable type

Any ideas how can I do this?

解决方案

Take a look at Activator.CreateInstance. For instance:

var instance = Activator.CreateInstance(typeof(T), new object[] { null, null });

Obviously replacing the nulls with appropriate values expected by one of the constructors of the type.

If you receive a compiler error about cannot convert object to type T, then include as T:

var instance = Activator.CreateInstance(typeof(T), 
                  new object[] { null, null }) as T;

这篇关于在C#泛型 - 我怎么可以创建一个变量类型与参数的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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