how to create an instance of class and set propert

2019-08-07 18:39发布

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 .

2条回答
一夜七次
2楼-- · 2019-08-07 18:41

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);
}
查看更多
We Are One
3楼-- · 2019-08-07 18:44
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);
}
查看更多
登录 后发表回答