如何创建类的实例并从Bag对象(如会话)设置属性 [英] how to create an instance of class and set properties from a Bag object like session

查看:176
本文介绍了如何创建类的实例并从Bag对象(如会话)设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该类将在运行时中声明,并且存储在 Bag 对象,例如 session ViewBag 。现在,我想创建该类的一个实例,并使用Bag数据设置其属性。我知道我应该使用 reflection ,但是我不知道是否有开箱即用的方法做这样的事情,或者我应该创建一个

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 .

推荐答案

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

这篇关于如何创建类的实例并从Bag对象(如会话)设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆