Activator.CreateInstance< T> VS新 [英] Activator.CreateInstance<T> Vs new

查看:112
本文介绍了Activator.CreateInstance< T> VS新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时有下列创建对象的两种方法之间的差异。

Is there any difference between following two ways of creating an object.

Student s1 = Activator.CreateInstance<Student>();
Student s1 = new Student();

  • 有没有在构造方法被调用或初始化内存有什么区别?
  • 在按我的理解,第一种方法看起来完全是多余的。如果程序员知道数据类型在设计时,他会用第二种方法。
  • 推荐答案

    激活的此重载。的CreateInstance 方法由编译器来实现通过使用泛型类型参数指定类型的实例。

    This overload of the "Activator.CreateInstance" method is used by compilers to implement the instantiation of types specified by type parameters using generics.

    假设你有下面的方法:

    public static T Factory<T>() where T: new()
    {
        return new T();
    }
    

    编译器将其转换回归新T();打电话的CreateInstance。

    The compiler will convert the "return new T();" to call "CreateInstance".

    在一般情况下,有没有用在申请code中的的CreateInstance,因为这个类型必须在编译时是已知的。如果类型是已知在编译时,正常实例化语法可以(在C#中新的运营商,新的Visual Basic中,gcnew在C ++中)。

    In general, there is no use for the CreateInstance in application code, because the type must be known at compile time. If the type is known at compile time, normal instantiation syntax can be used (new operator in C#, New in Visual Basic, gcnew in C++).

    详细信息:<一href="http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx">http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx

    这篇关于Activator.CreateInstance&LT; T&GT; VS新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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