如何找出表达式指定的类型?

发布于 2024-09-14 05:53:07 字数 175 浏览 5 评论 0原文

例如,假设我有一个方法,它将以下内容作为参数:

Expression<Func<T, object>> path

如何确定表达式中指定的“对象”的类型?更具体地说,我想确定它是否是集合类型(例如IEnumerable

For example, let's say I have a method that takes the following as a parameter:

Expression<Func<T, object>> path

How do I determine the type of the 'object' specified in the expression? More specifically, I'd like to determine if it's a collection type (eg. IEnumerable)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

饮湿 2024-09-21 05:53:07

您已经在使用泛型,为什么不继续使用呢?

void GetMemberType<TArg, TProperty>(Expression<Func<TArg, TProperty>> path)
{
    // Get the member ...
    var member = path.Body as MemberExpression;

    // ... Do whatever you want with the member ...

    // Now get the type
    var memberType = typeof(TProperty);
}

You're already using generics, so why not go all the way?

void GetMemberType<TArg, TProperty>(Expression<Func<TArg, TProperty>> path)
{
    // Get the member ...
    var member = path.Body as MemberExpression;

    // ... Do whatever you want with the member ...

    // Now get the type
    var memberType = typeof(TProperty);
}
和影子一齐双人舞 2024-09-21 05:53:07

或者,您可以执行类似以下操作(这更符合您的泛型类型参数):

// Get your expression
// (probably already provided as an arg to one of your methods, I'm willing to bet)
Expression<Func<T, object>> path = ...

var memberExpr = path.Body as MemberExpression;
var member = memberExpr.Member;

Type type;

if (member is FieldInfo)
{
    var field = member as FieldInfo;
    type = field.FieldType;
}

if (member is PropertyInfo)
{
    var property = member as PropertyInfo;
    type = property.PropertyType;
}

Alternatively, you could do something like the following (which is more inline with you generic type arguments):

// Get your expression
// (probably already provided as an arg to one of your methods, I'm willing to bet)
Expression<Func<T, object>> path = ...

var memberExpr = path.Body as MemberExpression;
var member = memberExpr.Member;

Type type;

if (member is FieldInfo)
{
    var field = member as FieldInfo;
    type = field.FieldType;
}

if (member is PropertyInfo)
{
    var property = member as PropertyInfo;
    type = property.PropertyType;
}
戒ㄋ 2024-09-21 05:53:07

Expression.Type 将回答这个问题(表达式的“结果”类型)。

为了更深入、更普遍地挖掘,您需要根据 Expression 实例的实际、运行时和类型来考虑不同的可能性 - 其中许多 Expression 的子类型您实际上有。

Expression.Type will answer this (the "result" type of the expression).

To dig deeper and more generally you will need to consider different possibilities depending on the actual, runtime, type of the Expression instance—which of the many subtypes of Expression do you actually have.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文