简体   繁体   English

Linq Expression属性类型

[英]Linq Expression property type

I have a linq expression defined as follows: 我有一个linq表达式定义如下:

private void GetMyPropertyType<T>(Expression<Func<T, object>> expression)
{
    // some code
    ----- HERE -----
}

which is called as 被称为

GetMyPropertyType<SomeType>(x => x.Age);

Now I want to know what the type is of "Age" at the position marked as "HERE". 现在,我想知道在标记为“ HERE”的位置上“ Age”的类型是什么。 The closest I've gotten is:" 我得到的最接近的是:“

expression.Body.Member.ToString()

which returns the value Int64 Age that I can then split and only take the first part of. 它返回的值是Int64 Age ,然后我可以拆分该值,并且只使用第一部分。 The problem however is that I want to get the full path ( System.Int64 ) which it only returns for certain types (like String ). 但是,问题是我想获取完整路径( System.Int64 ),该路径仅针对某些类型(如String )返回。 Am I missing a completely obvious method? 我是否缺少一种完全显而易见的方法? Or should I be doing it in this very ugly fashion? 还是我应该以这种非常丑陋的方式来做?

Thanks in advance for any help. 在此先感谢您的帮助。

You can use Expression.Type to find out the static type of the expression. 您可以使用Expression.Type找出Expression.Type的静态类型。 However, because you've got Expression<Func<T, object>> you've actually got a conversion expression around the property expression, so you need to remove that first. 但是,由于您拥有Expression<Func<T, object>> ,因此实际上在属性表达式周围有了一个转换表达式,因此您需要先将其删除。 Here's some sample code which works for the simple cases I've tried: 这是一些示例代码,适用于我尝试过的简单情况:

using System;
using System.Linq.Expressions;

class Person
{
    public int Age { get; set; }
    public string Name { get; set; }
}

class Test
{
    static void Main(string[] args)
    {
        ShowMemberType<Person>(p => p.Age);
        ShowMemberType<Person>(p => p.Name);
    }

    static void ShowMemberType<T>(Expression<Func<T, object>> expression)
    {
        var body = expression.Body;
        // Unwrap the conversion to object, if there is one.
        if (body.NodeType == ExpressionType.Convert)
        {
            body = ((UnaryExpression)body).Operand;
        }
        Console.WriteLine("Type: {0}", body.Type);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM