how to create an instance of class and set properties from a Bag object like session

徘徊边缘 提交于 2020-01-05 09:27:34

问题


the class will be declared in runtime and values are stored in a Bag object like session or ViewBag . Now I want to create an instance of the class and set it's properties using Bag data . I know that I should use reflection , but I don't know if there is any method out of box that does such things or I should create one ?

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

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

instance = ? // how to set properties using session

the class is not available in design time and application has no idea what its properties are .


回答1:


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



回答2:


ThaT'S works perefectly, ssee up 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);
}


来源:https://stackoverflow.com/questions/13050995/how-to-create-an-instance-of-class-and-set-properties-from-a-bag-object-like-ses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!