protected static T CreateNewInstance<T>() where T : new() 
        { 
            return new T(); 
        }
可以看懂,细节不知道是啥意思。比如 where T : new() 请问这是什么写法,请详细的讲一讲。这是lamd表达式吗?

解决方案 »

  1.   

    还有一个问题,如果想实例化一个带参数的构造函数,怎么写?
    protected static T CreateNewInstance<T>(string s) where T : new() 
            { 
                return new T(s); 
            }这样写报错!
      

  2.   

    where T: new()
    where后的称为泛型约束,这里约束泛型参数T必须具有无参的构造函数
      

  3.   

    very helpful if your generic type must create an instance of the type parameter, as you cannot assume the format of custom constructors. Note that this constraint must be listed last on a multiconstrained type. 
      

  4.   


    那请问还有什么办法是可以把类当作参数传递的?
    我想把类名当作参数来传递一个方法,然后在方法里通过类名来实例化(构造函数有参),然后做其他的操作。比如:Class BaseClass
    {
    }Class A: BaseClass
    {
    }Class B : BaseClass
    {
    }Method:Void Method (类名数组)
    {
       \\Step 1 :实例化
       \\ Step 2: 其他操作
    }如果把类名写个string类型的话 传递一个string 数组,通过反射可以实现,但是我觉得不太好
      

  5.   

    有没有构造参数取决于你的返回类型,如果你直接写成T是不能给构造函数添加参数的,但是如果你现在有一个具体的类,比如Person,里面有一个构造方法Person(string name),那么你的代码可以写成protected static Person CreateInstrance<T>(string a) where T : new()
            {
                return new Person(a);
            }
      

  6.   

    嗯,T表示泛型,本来可以为Object的。但是为了确保约束T的范围。后面用where T: new();
    来约束,或者是需要这个泛型是无参的构造函数。
    protected static T CreateNewInstance<T>(string s) where T : String
    {
    return new T();
    }
      

  7.   

    那楼主这样吧
    protected static T CreateNewInstance<T>(T t) where T : new()
    {
    //t的其他操作。之后再还回出去
    return t;}
      

  8.   

    解决方法:
    protected static object CreateNewInstance<T>(string s)

        return Activator.CreateInstance(typeof(T), new object[] { s });            
    }谢谢大家指点!
      

  9.   

    何必再包一层?用 Activator.CreateInstance<T> 
      

  10.   

    何必再包一层?用 Activator.CreateInstance<T>