简体   繁体   English

如何将参数传递给 Activator.CreateInstance<T> ()

[英]How to Pass Parameters to Activator.CreateInstance<T>()

I want to create an instance of a type that I specify in a generic method that I have.我想创建一个我在我拥有的泛型方法中指定的类型的实例。 This type has a number of overloaded constructors.这种类型有许多重载的构造函数。 I'd like to be able to pass arguments to the constructors, but我希望能够将参数传递给构造函数,但是

Activator.CreateInstance<T>()

doesn't see to have this as an option.不认为有这个选项。

Is there another way to do it?还有另一种方法吗?

是的。

(T)Activator.CreateInstance(typeof(T), param1, param2);

There is another way to pass arguments to CreateInstance through named parameters.还有另一种通过命名参数将参数传递给 CreateInstance 的方法。

Based on that, you can pass a array towards CreateInstance .基于此,您可以将数组传递给CreateInstance This will allow you to have 0 or multiple arguments.这将允许您有 0 个或多个参数。

public T CreateInstance<T>(params object[] paramArray)
{
  return (T)Activator.CreateInstance(typeof(T), args:paramArray);
}

Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.请记住,在 Activator.CreateInstance 上传递参数与无参数创建相比具有显着的性能差异。

There are better alternatives for dynamically creating objects using pre compiled lambda.使用预编译的 lambda 动态创建对象有更好的选择。 Of course always performance is subjective and it clearly depends on each case if it's worth it or not.当然,性能始终是主观的,它显然取决于每种情况是否值得。

Details about the issue on this article. 关于本文问题的详细信息。

Graph is taken from the article and represents time taken in ms per 1000 calls.图表取自文章,表示每 1000 次调用所花费的时间(以毫秒为单位)。

性能对比

As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5).作为 Activator.CreateInstance 的替代方案,链接 url 中的 FastObjectFactory 比 Activator 更好(从 .NET 4.0 开始,明显优于 .NET 3.5。没有使用 .NET 4.5 完成测试/统计)。 See StackOverflow post for stats, info and code:有关统计信息、信息和代码,请参阅 StackOverflow 帖子:

How to pass ctor args in Activator.CreateInstance or use IL? 如何在 Activator.CreateInstance 中传递 ctor args 或使用 IL?

public class AssemblyLoader<T>  where T:class
{
    public void(){
        var res = Load(@"C:\test\paquete.uno.dos.test.dll", "paquete.uno.dos.clasetest.dll") 
    }

    public T Load(string assemblyFile, string objectToInstantiate) 
    {
        var loaded = Activator.CreateInstanceFrom(assemblyFile, objectToInstantiate).Unwrap();

        return loaded as T;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM