[英]C# creating instance of class and set properties by name in string
我有問題 我想按名稱創建類的實例。 我發現了Activator.CreateInstance
http://msdn.microsoft.com/zh-cn/library/d133hta4.aspx ,並且工作正常,我發現了這一點:我也通過使用字符串值進行反射來設置屬性 。
但是如何同時做這件事? 我的意思是,我知道類的名稱,我知道該類中的所有屬性,並且都在字符串中。 例如:
string name = "MyClass";
string property = "PropertyInMyClass";
如何創建實例並為屬性設置一些值?
您可以使用反射:
using System;
using System.Reflection;
public class Foo
{
public string Bar { get; set; }
}
public class Program
{
static void Main()
{
string name = "Foo";
string property = "Bar";
string value = "Baz";
// Get the type contained in the name string
Type type = Type.GetType(name, true);
// create an instance of that type
object instance = Activator.CreateInstance(type);
// Get a property on the type that is stored in the
// property string
PropertyInfo prop = type.GetProperty(property);
// Set the value of the given property on the given instance
prop.SetValue(instance, value, null);
// at this stage instance.Bar will equal to the value
Console.WriteLine(((Foo)instance).Bar);
}
}
如果您有System.TypeLoad Exception,則您的類名錯誤。
對於Type.GetType方法,必須輸入程序集限定名稱 。 那就是項目名稱,例如: GenerateClassDynamically_ConsoleApp1.Foo
如果它在另一個程序集中,則jou必須在逗號后輸入程序集名稱(詳細信息請參見https://stackoverflow.com/a/3512351/1540350 ): Type.GetType(“ GenerateClassDynamically_ConsoleApp1.Foo,GenerateClassDynamically_ConsoleApp1”);
Type tp = Type.GetType(Namespace.class + "," + n.Attributes["ProductName"].Value + ",Version=" + n.Attributes["ProductVersion"].Value + ", Culture=neutral, PublicKeyToken=null");
if (tp != null)
{
object o = Activator.CreateInstance(tp);
Control x = (Control)o;
panel1.Controls.Add(x);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.