2012-10-24 38 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); 
} 
相關問題