1
我有一段代碼,看起來像這樣:使用where子句+ args的新約束?
public static T CreateSomething<T>(SomeType a) where T : SomeMicrosoftBaseClass, new()
{
var newElement = new T { SomeProperty = a};
DoStuff();
return newElement;
}
,現在我需要改變的代碼,所以我可以傳遞給SomeMicrosoftBaseClass的構造布爾參數 - 我只能在施工設置。
「新()」的約束,需要一個公共無參數的構造函數,因爲我不能用一個接口或修改SomeMicrosoftBaseClass,我使用反射像這樣:
var newElement = (T) (typeof (T).GetConstructor(new Type[] { typeof(SomeType) }).Invoke(new object[] { a }));
有人可以建議一個更優雅的方式來做到這一點?
只是知道Activate.CreateInstance是比較新的令人難以置信的慢() – JTtheGeek 2011-07-11 23:24:54