您可以使用反射:
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