首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从重写的属性中动态获取值

从重写的属性中动态获取值
EN

Stack Overflow用户
提问于 2015-11-21 03:57:26
回答 1查看 56关注 0票数 0

我希望能够在运行时使用反射动态获取覆盖属性的值。例如,

代码语言:javascript
复制
class A {
    public virtual int Foo => 5;

    //This implementation doesn't work
    public int ParentFoo => (int)this.GetType().BaseType.GetProperty(nameof(Foo)).GetValue(this); 
}

class B : A {
    public override int Foo => 7;
}

var test = new B();
Console.WriteLine(test.Foo);       //"7"
Console.WriteLine(test.ParentFoo); //Should display "5"

这样做的要点是类型层次结构相当深,我不希望扩展器每次都必须使用完全相同的逻辑(public int ParentFoo => base.Foo;)重新实现ParentFoo。我不介意为反射付出性能成本--这个属性不需要是高性能的。

是否有可能使用反射来完成我在这里所需的功能?

EN

回答 1

Stack Overflow用户

发布于 2015-11-21 05:18:02

可以始终使用反射为属性调用原始定义类的方法。这不是个好主意。下面的代码说明了这个概念,但不值得战斗,也不应该让它值得战斗。

代码语言:javascript
复制
void Main()
{
    var a = new A();
    Console.WriteLine(GetNoVCall<A, int>(a, z => z.Foo)); // prints 5
    var b = new B();
    Console.WriteLine(GetNoVCall<A, int>(b, z => z.Foo)); // prints 5
    Console.WriteLine(GetNoVCall<B, int>(b, z => z.Foo)); // prints 5
}

class A
{
    public virtual int Foo { get { return 5; } }
}

class B : A
{
    public override int Foo { get { return 7; } }
}

public static TProp GetNoVCall<TClass, TProp>(TClass c, Expression<Func<TClass, TProp>> f)
{
    var expr = f.Body as MemberExpression;
    var prop = expr.Member as PropertyInfo;
    var meth = prop.GetGetMethod(true);
    var src = expr.Expression as ParameterExpression;

    if (src == null || prop == null || expr == null)
        throw new Exception();

    var dyn = new DynamicMethod("GetNoVCallHelper", typeof(TProp), new Type[]{ typeof(TClass) }, typeof(string).Module, true);
    var il = dyn.GetILGenerator();
    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Call, meth);
    il.Emit(OpCodes.Ret);

    return ((Func<TClass, TProp>)dyn.CreateDelegate(typeof(Func<TClass, TProp>)))(c);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33835071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档