1


比如一个实体类,我想在运行时给他增加一个属性,应该怎么办?

垃圾帖?
提问于2009-02-19 00:33:37
60 1 2
添加评论
2


通过.net的reflection是可以做到在runtime时候动态创建属性的(甚至一个新的类型)。需要获得当前类型的TypeBuilder实例,使用DefineProperty添加一个属性,不过有点麻烦,需要分别为getter和setter分别设置,并且还有一些额外的IL代码操作。具体办法参考在System.Reflection.Emit命名空间的TypeBuilder类和DefineProperty方法。示例代码添加一个“MyProperty”属性:

string propertyName = "MyProperty";

// Generate a private field
FieldBuilder field = typeBuilder.DefineField("_" + propertyName, 
typeof(string),     
FieldAttributes.Private);
// Generate a public property
PropertyBuilder property = 
    typeBuilder.DefineProperty(propertyName,
                     PropertyAttributes.None,
                     typeof(string),
                     new Type[] { typeof(string) });

// The property set and get methods require a special set of attributes:
MethodAttributes GetSetAttr =
    MethodAttributes.Public |
    MethodAttributes.HideBySig;

// Define the "get" accessor method for current private field.
MethodBuilder currGetPropMthdBldr =
    typeBuilder.DefineMethod("get_value",
                               GetSetAttr,
                               typeof(string),
                               Type.EmptyTypes);

// Intermediate Language stuff...
ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
currGetIL.Emit(OpCodes.Ldarg_0);
currGetIL.Emit(OpCodes.Ldfld, field);
currGetIL.Emit(OpCodes.Ret);

// Define the "set" accessor method for current private field.
MethodBuilder currSetPropMthdBldr =
    typeBuilder.DefineMethod("set_value",
                               GetSetAttr,
                               null,
                               new Type[] { typeof(string) });

// Again some Intermediate Language stuff...
ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
currSetIL.Emit(OpCodes.Ldarg_0);
currSetIL.Emit(OpCodes.Ldarg_1);
currSetIL.Emit(OpCodes.Stfld, field);
currSetIL.Emit(OpCodes.Ret);

// Last, we must map the two methods created above to our PropertyBuilder to 
// their corresponding behaviors, "get" and "set" respectively. 
property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr);
永久链接 | 垃圾帖?
回答于2009-02-19 12:11:12
348 2 10
评论 (1)




Made with Django.

当前版本: R-0127-20090523

cc-wiki