gpt4 book ai didi

c# - 使用反射获取baseclass属性值-与this.Property相反的base.Property

转载 作者:行者123 更新时间:2023-12-03 23:24:19 24 4
gpt4 key购买 nike

我想知道是否可能发生这样的事情:我已经重写了自动实现的基类的属性。我已在替代中提供了逻辑,以针对默认设置解决“缺失”属性。

现在,我想使用反射来检查是否使用默认值或某个“实际”值。换句话说,我需要检查base.Property是否为null,但是要使用反射。这是行不通的,它只是获取子类值(根据默认值解析,因此不为null)。

var property = this.GetType().GetProperty(e.PropertyName);
if(property.GetValue(this, null) == null))
OnPropertyChanged(e.PropertyName);


还尝试了:

var property = this.GetType().BaseType.GetProperty(e.PropertyName);
if(property.GetValue(this, null) == null))
OnPropertyChanged(e.PropertyName);


是否可以使用反射来访问基类值?

更新:

根据评论的建议,我尝试了以下方法,只是为了踢球。

var method1 = this.GetType().BaseType.GetMethods().First(x => x.Name.Contains(e.PropertyName));
var method = this.GetType().BaseType.GetProperty(e.PropertyName).GetGetMethod();
var methodValue = method1.Invoke(this, null);


这两个都仍返回“派生”值,而同时 base.Property返回null。

最佳答案

尽管据我所知,不发出自己的IL是没有办法的,但是基本上可以使用call指令而不是callvirt

请注意,如果您需要花些时间才能完成设计工作,那么这表明您可能在某处做错了!

无论如何,这是一个人为的例子。 (为简洁起见,省略了错误检查等。)

var derived = new DerivedClass();
Console.WriteLine(derived.GetBaseProperty("Prop")); // displays "BaseProp"

// ...

public class BaseClass
{
public virtual string Prop { get; set;}
}

public class DerivedClass : BaseClass
{
public override string Prop { get; set;}

public DerivedClass()
{
base.Prop = "BaseProp";
this.Prop = "DerivedProp";
}

public object GetBaseProperty(string propName)
{
Type t = this.GetType();
MethodInfo mi = t.BaseType.GetProperty(propName).GetGetMethod();

var dm = new DynamicMethod("getBase_" + propName, typeof(object), new[] { typeof(object) }, t);

ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, mi);
if (mi.ReturnType.IsValueType) il.Emit(OpCodes.Box, mi.ReturnType);
il.Emit(OpCodes.Ret);

var getBase = (Func<object, object>)dm.CreateDelegate(typeof(Func<object, object>));
return getBase(this);
}
}

关于c# - 使用反射获取baseclass属性值-与this.Property相反的base.Property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6712466/

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