[英]How to Activator.CreateInstance a type which have not constructors?
[英]Activator.CreateInstance - How to create instances of classes that have parameterized constructors
我已經在網上閱讀了一些關於這個主題的內容,但發現沒有一個對我有用。 我要做的是創建一個運行時類型的類。
我使用Activator.CreateInstance
,它適用於具有不包含參數的構造函數的類。 對於那些有參數的人會引發異常,有沒有辦法繞過這個?
我非常樂意將空值或空值傳遞給ctor,只要我可以創建類本身。
有一個重載接受參數作為params object[]
:
object obj = Activator.CreateInstance(typeof(StringBuilder), "abc");
這會嗎? 或者,您可以使用反射來查找正確的構造函數:
Type[] argTypes = new Type[] {typeof(string)};
object[] argValues = new object[] {"abc"};
ConstructorInfo ctor = typeof(StringBuilder).GetConstructor(argTypes);
object obj = ctor.Invoke(argValues);
我最終最終做了類似的事情 - 一些評論員無論如何都暗示了這個解決方案。
我基本上遍歷了所有可用的構造函數並選擇了最簡單的構造函數。 然后我創建了空數據以傳遞到ctor(因為我使用它來處理這種方法很好)
部分代碼看起來有點像這樣
// If we have a ctor that requires parameters then pass null values
if (requiresParameters)
{
List<object> parameters = new List<object>();
ParameterInfo[] pInfos = constructorInfos[0].GetParameters();
foreach (ParameterInfo pi in pInfos)
{
parameters.Add(createType(pi.ParameterType));
}
return constructorInfos[0].Invoke(parameters.ToArray());
}
我正在使用這種方法解決我遇到的問題 ,它似乎正如我希望的那樣工作。 :)
object instance = Activator.CreateInstance(
typeof(OpCode),
BindingFlags.NonPublic | BindingFlags.Instance,
default(Binder),
new object[] { stringname, pop, push, operand, type, size, s1, s2, ctrl, endsjmpblk, stack },
default(CultureInfo));
Activator.CreateInstance也有一大堆重載,你可能想要檢查的是(Type type,params object [] args)。 只需為此調用的第二個參數提供所需的構造函數參數即可。
確保你在這里處理異常,因為很容易傳遞不正確的參數或者稍后在類型的構造函數中更改某些東西會破壞它。
作為Activator.CreateInstance的替代方案,鏈接url中的FastObjectFactory比Activator更好(從.NET 4.0開始,明顯優於.NET 3.5。沒有使用.NET 4.5進行測試/統計)。 有關統計信息,信息和代碼,請參閱StackOverflow帖子。 請注意,可能需要根據ctor參數的數量進行一些修改。 提供的代碼僅允許1 ctor param,但可以修改為超過1.請參閱代碼中的注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.