当前位置: 首页 > 编程语言 > C#

使用Reflection.Emit覆盖属性定义分享

时间:2023-04-10 18:41:10 C#

使用Reflection.Emit覆盖属性定义放;}}publicclassProxy:ClassToBeProxied{[AttributeToBeAdded]publicoverrideobjectProperty1{get{//做一些其他事情来返回对象-即从数据库中获取它returnnull;//stub}set{//做一些其他的事情来设置对象-即,将它保存到数据库}}}如果我所做的只是拦截get和set方法,那么这是有效的:PropertyInfoinfo=typeof(ClassToBeProxied)。GetProperty("Property1",BindingFlags.Public|BindingFlags.Instance);{MethodBuilderpGet=typeBuilder.DefineMethod("get_"+info.Name,MethodAttributes.Virtual|MethodAttributes.Public|MethodAttributes.SpecialName|MethodAttributes.HideBySig,info.PropertyType,Type.EmptyTypes);ILGeneratorpILGet=pGet.GetILGenerator();//代理对象pILGet.Emit(OpCodes.Ldarg_0);//数据库pILGet.Emit(OpCodes.Ldfld,database);//代理对象pILGet.Emit(OpCodes.Ldarg_0);//要查找的ObjectIdpILGet.Emit(OpCodes.Ldfld,f);pILGet.Emit(OpCodes.Callvirt,typeof(MongoDatabase).GetMethod("查找",BindingFlags.Public|BindingFlags.Instance,null,newType[]{typeof(ObjectId)},null).MakeGenericMethod(info.PropertyType));pILGet.Emit(OpCodes.Ret);MethodBuilderpSet=typeBuilder.DefineMethod("set_"+info.Name,MethodAttributes.Virtual|MethodAttributes.Public|MethodAttributes.SpecialName|MethodAttributes.HideBySig,null,newType[]{info.PropertyType});ILGeneratorpILSet=pSet.GetILGenerator();pILSet.Emit(OpCodes.Ldarg_0);pILSet.Emit(OpCodes.Ldarg_1);pILSet.Emit(OpCodes.Ldarg_0);pILSet.Emit(OpCodes.Ldfld,数据库);pILSet.Emit(OpCodes.Call,typeof(ProxyBuilder).GetMethod("SetValueHelper",BindingFlags.Public|BindingFlags.Static,null,newType[]{typeof(object),typeof(MongoDatabase)},null));pILSet.Emit(OpCodes.Stfld,f);pILSet.Emit(操作码s.Ret);//编辑:添加修复newProp.SetSetMethod(pSet);newProp.SetGetMethod(pGet);但我需要做的是向属性添加一个属性,我不知道该怎么做。如果我添加一个新的PropertyDefinition:PropertyBuildernewProp=typeBuilder.DefineProperty(info.Name,PropertyAttributes.None,info.PropertyType,Type.EmptyTypes);newProp.SetCustomAttribute(newCustomAttributeBuilder(typeof(AttributeToBeAdded).GetConstructor(Type.EmptyTypes),Type.EmptyTypes,newFieldInfo[0],newobject[0]));然后在结果类型上调用GetProperties(),将出现两个同名的属性。但是,如果我手动构建代码(如上例所示)并调用typeof(Proxy).GetProperties(),我只会看到一个属性(派生类属性)。这是我需要的行为,但我似乎无法通过Reflection.Emit到达那里。如果我需要添加更多信息以使问题更清楚,请告诉我。所以答案是添加这个:newProp.SetSetMethod(pSet);newProp.SetGetMethod(pGet);请参阅已编辑的问题。答案类型与http://www.gutgames.com/post/Overridding-a-Property-With-ReflectionEmit.aspx相矛盾,但它似乎有效。以上就是C#学习教程:使用Reflection.Emit重写属性定义分享全部内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: