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

标签 c# reflection properties

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

现在,我想使用反射来检查是否使用默认值或某个“实际”值。换句话说,我需要检查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/

相关文章:

java - 如何处理 *.txt 文件中缺少键的异常?属性文件?

javascript - 使用js ajax的参数调用c#方法

c# - 刷新一个按钮

c# - Visual Studio 2017 + .Net Core 2 测试不可执行

json - 将嵌套接口(interface){}解码为用户提供的结构指针

c# - 如何从对包含类型的引用中获取 ICollection<> 属性的名称?

c# - 如何使用 .Net Core 在 Linux 上从同一网络的远程计算机获取 mac 地址

java - 使用java反射实例化接口(interface)?

c# - 是否可以从基础对象的列表中访问子对象属性?

对象的 Javascript getter 和 setter,而不是对象属性