C#创建类的实例和按字符串名称设置属性
我有一些问题。我想按名称创建类的实例。 我发现Activator.CreateInstance
http://msdn.microsoft.com/en-us/library/d133hta4.aspx它工作正常,我发现这个: Setting a property by reflection with a string value 了。C#创建类的实例和按字符串名称设置属性
但如何做到这一点?我的意思是,我知道班级的名字,我知道班上的所有属性,我有这个字符串。 例如:
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);
}
}
@Darin,我测试了相同的代码,它返回的错误是“无法从程序集'GenerateClassDynamically_ConsoleApp1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'加载类型'Foo'”。 。异常类型是“System.TypeLoad异常”。我不明白它为什么出现? – 2014-07-25 09:23:15
@Darin,我测试了相同的代码,并且它返回的错误是“无法从程序集'GenerateClassDynamically_ConsoleApp1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'加载类型'Foo'”。 。异常类型是“System.TypeLoad异常”。我不明白它为什么出现?请帮帮我。我有同样的要求,它获得一个SAP服务,我需要生成类并向该类动态添加属性,并将其发送回服务以获取响应数据。 – 2014-07-25 09:28:35
如果你有System.TypeLoad例外,你的类名是错误的。
要使用Type.GetType方法,您必须输入装配限定名称。 与该项目名称例如:GenerateClassDynamically_ConsoleApp1.Foo
如果是在另一个组装柔逗号后必须输入组件名称(在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);
}
你几乎不能做这样的事情。对象的创建和设置属性与Reflection的观点是完全不同的。此外,你将不得不分别设置每个属性。当然,你可以创建一个帮助函数,它会把你的字符串拆分,分解,然后创建对象并设置proeprties。我认为它应该为你做诡计。 – quetzalcoatl 2012-08-14 18:54:32