2012-10-24 22 views
1

该类将在runtimevalues中声明,对象存储为sessionViewBag。现在我想创建该类的实例,并使用Bag数据将其属性设置为。我知道我应该使用reflection,但我不知道是否有任何方法开箱即用那样做的事情或我应该创建一个如何创建类实例并从Bag对象中设置属性,如会话

session["Foo"] = "foo"; 
session["Bar"] = "bar"; 

var instance = System.Activator.CreateInstance(Type.GetType(className)); 

instance = ? // how to set properties using session 

该类在设计时不可用,应用程序不知道它的属性是什么。

回答

4
Type myType = Type.GetType(className); 
var instance = System.Activator.CreateInstance(myType); 
PropertyInfo[] properties = myType.GetProperties(); 

foreach (var property in properties) 
{ 
    property.SetValue(instance, session[property.Name], null); 
} 
+0

class in not available in design time,and application does not know what what its properties are –

+0

This should work –

0

这就是工程perefectly,SSEE向上 类型的myType = Type.GetType(类名);

var instance = System.Activator.CreateInstance(myType); 
PropertyInfo[] properties = myType.GetProperties(); 

foreach (var property in properties) 
{ 
    property.SetValue(instance, session[property.Name], null); 
}