私が考えることができる唯一の方法は、(派生クラスでbase.Something
を行うときと同様の)非仮想呼び出しをクラスプロパティゲッターに行うことです。
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
public static class Utils
{
public static TValue GetClassValue<TSource, TValue>(this TSource source, Expression<Func<TSource, TValue>> selector)
where TSource : class
{
Func<TSource, TValue> getValue = null;
if (source.GetType() != typeof(TSource))
{
var propertyAccessor = selector.Body as MemberExpression;
if (propertyAccessor != null)
{
var propertyInfo = propertyAccessor.Member as PropertyInfo;
if (propertyInfo != null)
{
var getMethod = propertyInfo.GetGetMethod();
if (getMethod != null && getMethod.IsVirtual)
{
var dynamicMethod = new DynamicMethod("", typeof(TValue), new[] { typeof(TSource) }, typeof(Utils), true);
var il = dynamicMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Call, getMethod, null);
il.Emit(OpCodes.Ret);
getValue = (Func<TSource, TValue>)dynamicMethod.CreateDelegate(typeof(Func<TSource, TValue>));
}
}
}
}
if (getValue == null)
getValue = selector.Compile();
return getValue(source);
}
}
:純粋なC#または反射して、私が代わりに通常の
Callvirt
の
Call
IL命令を発するように
System.Reflection.Emit
LCG(軽量コード生成)を利用し、次のヘルパーメソッドになってしまったことを実行する方法はありませんので、
それはこのように、単一およびコレクション型ナビゲーションプロパティの両方に使用することができます。
if (myUser.GetClassValue(x => x.Tags) == null)
@Tuco。そのエンティティを読み込むためのいくつかの方法(いくつかは 'Include'を持たないものもあります)があると、いくつかの外部コードが利用可能な子コレクションに適応できるはずです。 – Mart