![](/img/trans.png)
[英]Activator.CreateInstance - How to create instances of classes that have parameterized constructors
[英]How to Activator.CreateInstance a type which have not constructors?
例如:
class TestType
{
public int a;
public int b;
}
TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType;
那么obj.a==1
和obj.b==2
? 有人知道如何解決我的問題嗎?
不可能,試試吧
TestType obj = Activator.CreateInstance(typeof(TestType)) as TestType;
obj.a = 1;
obj.b = 2;
TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType;
這是重載Activator.CreateInstance(type,params object [] args); 其中args是構造函數的輸入。 因此,您可以使用Antoines解決方案或將測試類型類更改為:
TestType obj = Activator.CreateInstance(typeof(TestType), 1, 2) as TestType;
class TestType
{
public TestType(int a, int b)
{
this.a = a;
this.b = b;
}
public int a;
public int b;
}
你是混亂的事情。 語法new TestType { a=1, b=2 }
不調用構造函數。 它是調用隱式或默認構造函數並一次性設置某些屬性的快捷方式。 但是所有類都有構造函數。 至少是隱含的。
我不知道你的最終目標是什么,但如果你使用Activator
來創建一個實例,那么你可能在編譯時沒有這個類型。 因此,您無法通過類型本身訪問屬性,您需要調用PropertyInfo.SetValue
( https://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view= netframework-4.7.2 )
請參閱以下示例:
class TestType
{
public int a;
public int b;
}
void Main()
{
var typeName = typeof(TestType).FullName; // we have a string from here on
var type = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x.FullName == typeName); // get the type based on the name
var obj = Activator.CreateInstance(type); // object of this type, but without compile time type info
var member = type.GetField("a"); // we know, that this is a field, not a property
member.SetValue(obj, 1); // we set value to 1
member = type.GetField("b");
member.SetValue(obj, 2); // we set value to 2
Console.Write($"See values: a={((TestType)obj).a}, b={((TestType)obj).b}");
}
在最后一個代碼行中,我重新引入了編譯時類型,只是為了表明構造的對象具有我們期望它們設置的成員集。
通常,您很可能會查找擴展某些基類型或實現接口的類型,但例如,當您從配置中獲得完全限定的類型名稱時,可能就是這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.