[英]Creating instance of type without default constructor in C# using reflection
[英]Creating an instance of a type using reflection
我正在嘗試使用反射來創建我的一個類的實例。 類的接口(IInstructions)具有如下所示的一個變量。
string[] Operands { get; set; }
我正在嘗試使用已設置操作數變量的反射來創建此類的實例。 我到目前為止獲得的代碼如下所示。
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Console.WriteLine(operands[0]);
foreach (Assembly a in assemblies)
{
Type[] typeArray = a.GetTypes();
foreach (Type type in typeArray)
{
if (opcode.Equals(type.Name, StringComparison.InvariantCultureIgnoreCase))
{
Object dynamicObj = Activator.CreateInstance(type);
instruction = (IInstructionWithOperand)dynamicObj;
}
}
}
到目前為止,這將搜索已加載的程序集,並檢索該程序集的正確程序集和類型。 但是,我不確定如何為此類型設置變量並正確創建它的實例?
如果類型始終為IInstructionWithOperand
則可以聲明
IInstructionWithOperand instruction;
然后完全按照您的要求進行分配:
instruction = (IInstructionWithOperand)dynamicObj;
或者,假設上面的所有代碼都在一個函數內。 您可以使IInstructionWithOperand
函數的返回類型,例如
IInstructionWithOperand GetInstruction(string opcode)
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Console.WriteLine(operands[0]);
foreach (Assembly a in assemblies)
{
Type[] typeArray = a.GetTypes();
foreach (Type type in typeArray)
{
if (opcode.Equals(type.Name, StringComparison.InvariantCultureIgnoreCase))
{
Object dynamicObj = Activator.CreateInstance(type);
return (IInstructionWithOperand)dynamicObj;
}
}
}
}
您不必在函數內聲明變量。 調用該函數時,它將如下所示:
var instruction = GetInstruction(someOpCode);
聲明的instruction
類型為IInstructionWithOperand
。
無論如何,這可能是一個好主意,因為它將使您的部分代碼分開。 一個函數創建實現IInstructionWithOperand
的類的實例,而另一個函數(或類)使用它來執行某些操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.