Activator.CreateInstance 和 New

Activator.CreateInstance 用来动态创建一个实例对象,可以是有参数,也可以是无参数

 

public T CreateWithActivator<T>() 可以编译成功,但是如果T没有无参构造函数,一样会报错

所以最好给泛型加约束 public T CreateWithNew<T>() where T : new()

注意值类型有无参构造函数, int i =new int();

T t=(T)Activator.CreateInstance(typeof(T), "zz"); 需要强转一下
T t =Activator.CreateInstance<T>() 则不需要转换
 
public class GenericTests
{
    public T CompileError<T>() // compile error CS0304
    {
        return new T();
    }
 
    public T CreateWithNew<T>() where T : new() // builds ok
    {
        return new T();
    }
 
    public T CreateWithActivator<T>() // builds ok
    {
        return Activator.CreateInstance<T>();
    }
}

  

posted @ 2021-12-31 03:08  zq爱生活爱代码  阅读(282)  评论(0编辑  收藏  举报