GetMethods()上未列出的扩展方法

时间:2016-08-10 10:46:37

标签: c# reflection

我在DateTime上有一个扩展方法:

public static DateTime? Year(this DateTime? datetime)
{
    return datetime;
}

另一个试图为此扩展方法构建CallExpression的人:

public static Expression<Func<TElementType, DateTime?>> SemanticYear<TElementType>(this Expression<Func<TElementType, DateTime?>> expr)
{

    MethodInfo method = typeof(DateTime?).GetMethods().Where(m => m.Name.Equals("Year"));
    //<<<<<< returns null!!

    Expression<Func<TElementType, DateTime?>> lambdaExpression = Expression.Lambda<Func<TElementType, DateTime?>>(
        Expression.Call(
            Expression.MakeMemberAccess(expr.Body, typeof(DateTime?).GetProperty("Value")),
            method
        ),
        expr.Parameters
    );

    return lambdaExpression;
}

为什么我无法获得DateTime?.Year扩展方法?

两种方法都在同一个编译单元中实现:

namespace Backend.Infrastructure.Linq
{
    public static partial class LinqTreeExtensions
    {

        public static DateTime? Year(this DateTime datetime)
        {
        //....
        }

        public static Expression<Func<TElementType, DateTime?>> SemanticYear<TElementType>(this Expression<Func<TElementType, DateTime?>> expr)
        {
        //.......
        }
    }
}

0 个答案:

没有答案