gpt4 book ai didi

.net - 使用 Reflection : Activator. CreateInstance 或 Inovking 构造函数 C# 创建对象

转载 作者:行者123 更新时间:2023-12-02 04:59:19 25 4
gpt4 key购买 nike

哪种使用反射创建对象的方法更好?

获取构造函数的引用并调用构造函数创建对象或

在类的类型上使用 Activator.CreateInstance

从某种意义上说,我们会选择一种方法而不是另一种方法有什么具体原因吗?如果是,在什么情况下。

我刚刚在学习反射(reflection),有这个问题。

最佳答案

他们做同样的事情。使用起来更容易 Activator.CreateInstance .

Creates an instance of the specified type using the constructor that best matches the specified parameters.

实际上,您可能会从使用 Activator 中获得一些性能优势,因为它在内部缓存了构造函数实例。如果您在一个循环中创建许多这样的代码,那么 Activator 代码很可能比简单的手工实现更优化。

关于.net - 使用 Reflection : Activator. CreateInstance 或 Inovking 构造函数 C# 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com