使用一个lambda,而不是一个字符串属性名称选择模型属性 [英] Select a model property using a lambda and not a string property name

查看:106
本文介绍了使用一个lambda,而不是一个字符串属性名称选择模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个类型的属性列表中该类型的集合导出到包括。我想做到这一点,而不使用字符串属性名。的类型的唯一的某些性能将被包括在列表中。我想要做的是这样的:

I'm building a list of properties of a type to include in an export of a collection of that type. I'd like to do this without using strings for property names. Only certain properties of the type are to be included in the list. I'd like to do something like:

exportPropertyList<JobCard>.Add(jc => jc.CompletionDate, "Date of Completion");

我该如何去实现这个通用Add方法?顺便说一句,该字符串是属性的描述。

How can I go about implementing this generic Add method? BTW, the string is the description of the property.

推荐答案

您可以通过检查传入的防爆pression获得PropertyInfo对象是这样的:

You can get the PropertyInfo object by examining the Expression passed in. Something like:

public void Add<T>(Expression<Func<T,object>> expression, string displayName)
{
    var memberExpression = expression.Body as MemberExpression;
    PropertyInfo prop = memberExpression.Member as PropertyInfo;
    // Add property here to some collection, etc ? 
}

这是一个不完全实现,因为我不知道你想要做的财产究竟是什么 - 但它确实展示了如何从一个防爆pression得到的PropertyInfo - 的PropertyInfo对象包含所有元数据财产。此外,一定要错误处理添加到上面把它应用在生产中code(即对前pression不是一个MemberEx pression等后卫)。

This is an uncomplete implementation, because I don't know what exactly you want to do with the property - but it does show how to get the PropertyInfo from an Expression - the PropertyInfo object contains all meta data about the property. Also, be sure to add error handling to the above before applying it in production code (ie. guards against the expression not being a MemberExpression, etc.).

这篇关于使用一个lambda,而不是一个字符串属性名称选择模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆