您可以使用反射:
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);
}
}
你几乎不能做这样的事情。对象的创建和设置属性与Reflection的观点是完全不同的。此外,你将不得不分别设置每个属性。当然,你可以创建一个帮助函数,它会把你的字符串拆分,分解,然后创建对象并设置proeprties。我认为它应该为你做诡计。 – quetzalcoatl 2012-08-14 18:54:32