Why do expressions in generic types refer to a constraint type instead of a runtime type?

The easiest way to ask this is to show an example (LinqPad) that demonstrates the problem:

void Main()
{
    GetProp<IFace>().DeclaringType.Dump(); // iface
    GetProp<C>().DeclaringType.Dump(); // iface
    GetProp().DeclaringType.Dump(); // c
}

public interface IFace { int A { get; set; } }

public class C : IFace { public int A { get; set; } }

public PropertyInfo GetProp<T>() where T : IFace
{
    return ExtractProperty((T x) => x.A);
}

public PropertyInfo GetProp()
{
    return ExtractProperty((C x) => x.A);
}

private PropertyInfo ExtractProperty<T, V>(Expression<Func<T, V>> exp)
{
    return (PropertyInfo) ((MemberExpression) exp.Body).Member;
}

I am intrigued by GetProp<C>using the property property on IFaceinstead of property on C. Can anyone explain this behavior? Looking at it IL code, I see that the generic version GetProp<T>uses ldtoken for the type IFace, but why is it implemented this way? Can someone point me to an excuse or specification for this behavior?

+4
source share
1 answer

Since the element search is performed at compile time.

x.A A .

. 7.4 :

N K T :

  • N:

    • T , N , (§10.1.5) T, N .
+4

Source: https://habr.com/ru/post/1529066/


All Articles