4

クラスはで宣言さruntimeれ、またはのようなオブジェクトvaluesに格納されます。次に、クラスのインスタンスを作成し、Bagデータを使用してそのプロパティを設定します 。私は使用する必要があることを知っていますが、そのようなことを行う箱から出してすぐに使用できる方法があるかどうかわかりませんか、それとも作成する必要がありますかBagsessionViewBagreflection

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

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

instance = ? // how to set properties using session

クラスは設計時に利用できず、アプリケーションはそのプロパティが何であるかを認識していません。

4

1 に答える 1

9
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);
}
于 2012-10-24T14:11:42.767 に答える