Skip to main content
 首页 » 编程设计

c#之如何创建类的实例并从 Bag 对象(如 session )设置属性

2024年02月20日13cyq1162

该类将在 runtime 中声明和 values存储在 Bag 中像session这样的对象或 ViewBag .现在我想创建一个类的实例并设置它的属性using Bag data。我知道我应该使用 reflection ,但我不知道是否有任何开箱即用的方法可以做这样的事情,或者我应该创建一个?

session["Foo"] = "foo"; 
session["Bar"] = "bar"; 
 
var instance = System.Activator.CreateInstance(Type.GetType(className)); 
 
instance = ? // how to set properties using session 

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

请您参考如下方法:

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); 
}