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

标签 c# reflection system.reflection viewbag activator

该类将在 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/

相关文章:

c# - 相同类型的多个框架 Windows 8 c#

c# - Entity Framework V4 : "Code Only" performance considerations

Java动态创建实例变量的对象数组

c# - .NET 反射依赖注入(inject)与多个容器

haskell - 何时在 Haskell 中毫无悔意地使用 CPS、共密度与反射

c# - 调试期间不显示图像

c# - "button_click"没有重载匹配委托(delegate) 'System.EventHandler'

c# - Type.GetMethod() 返回 null,即使方法确实存在

c# - 对 .NET 程序集进行沙盒化 - 上传 DLL,然后进行反射

c# - 从泛型类获取 ICollection 类型属性的列表