该类将在 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);
}
关于c# - 如何创建类的实例并从 Bag 对象(如 session )设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13050995/