gpt4 book ai didi

c# - 使用 Reflection.Emit 覆盖属性定义

转载 作者:太空狗 更新时间:2023-10-29 21:55:18 26 4
gpt4 key购买 nike

我正在尝试使用 Reflection.Emit (TypeBuilder) 实现此模式:

public class ClassToBeProxied
{
public virtual object Property1 { get; set; }
}

public class Proxy : ClassToBeProxied
{
[AttributeToBeAdded]
public override object Property1
{
get
{
//do something else to return the object - i.e get it from the database
return null; //stub
}
set
{
//do something else to set the object - i.e, save it to a database
}
}
}

如果我所做的只是拦截 get 和 set 方法,那么这会起作用:

PropertyInfo info = typeof(ClassToBeProxied).GetProperty("Property1", BindingFlags.Public | BindingFlags.Instance);
{
MethodBuilder pGet = typeBuilder.DefineMethod("get_" + info.Name, MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, info.PropertyType, Type.EmptyTypes);
ILGenerator pILGet = pGet.GetILGenerator();

//The proxy object
pILGet.Emit(OpCodes.Ldarg_0);
//The database
pILGet.Emit(OpCodes.Ldfld, database);
//The proxy object
pILGet.Emit(OpCodes.Ldarg_0);
//The ObjectId to look for
pILGet.Emit(OpCodes.Ldfld, f);
pILGet.Emit(OpCodes.Callvirt, typeof(MongoDatabase).GetMethod("Find", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(ObjectId) }, null).MakeGenericMethod(info.PropertyType));
pILGet.Emit(OpCodes.Ret);

MethodBuilder pSet = typeBuilder.DefineMethod("set_" + info.Name, MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new Type[] { info.PropertyType });
ILGenerator pILSet = pSet.GetILGenerator();
pILSet.Emit(OpCodes.Ldarg_0);
pILSet.Emit(OpCodes.Ldarg_1);
pILSet.Emit(OpCodes.Ldarg_0);
pILSet.Emit(OpCodes.Ldfld, database);
pILSet.Emit(OpCodes.Call, typeof(ProxyBuilder).GetMethod("SetValueHelper", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(object), typeof(MongoDatabase) }, null));
pILSet.Emit(OpCodes.Stfld, f);
pILSet.Emit(OpCodes.Ret);

//Edit: Added fix
newProp.SetSetMethod(pSet);
newProp.SetGetMethod(pGet);
}

但是我需要做的也是给Property添加一个属性。我不知道该怎么做。

如果我添加一个新的 PropertyDefinition:

PropertyBuilder newProp = typeBuilder.DefineProperty(info.Name, PropertyAttributes.None, info.PropertyType, Type.EmptyTypes);
newProp.SetCustomAttribute(new CustomAttributeBuilder(typeof(AttributeToBeAdded).GetConstructor(Type.EmptyTypes), Type.EmptyTypes, new FieldInfo[0], new object[0]));

然后在生成的类型上调用 GetProperties(),出现两个同名的属性。但是,如果我手动构建代码(如上例所示)并调用 typeof(Proxy).GetProperties(),则只有一个属性(派生类属性)可见。这是我需要的行为,但我似乎无法通过 Reflection.Emit 达到目标

如果我需要添加更多信息以使问题更清楚,请告诉我。

最佳答案

所以答案是添加这个:

newProp.SetSetMethod(pSet);
newProp.SetGetMethod(pGet);

查看编辑后的问题。

答案有点矛盾http://www.gutgames.com/post/Overridding-a-Property-With-ReflectionEmit/

但它似乎有效。

关于c# - 使用 Reflection.Emit 覆盖属性定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8720275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com