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

大城市里の小女人 提交于 2019-11-26 09:25:11

问题


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?


回答1:


Yes.

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



回答2:


There is another way to pass arguments to CreateInstance through named parameters.

Based on that, you can pass a array towards CreateInstance. This will allow you to have 0 or multiple arguments.

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



回答3:


Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.

There are better alternatives for dynamically creating objects using pre compiled 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.




回答4:


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). See StackOverflow post for stats, info and code:

How to pass ctor args in Activator.CreateInstance or use IL?



来源:https://stackoverflow.com/questions/2451336/how-to-pass-parameters-to-activator-createinstancet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!