C#多表达式参数 [英] c# multiple expression parameteres

查看:41
本文介绍了C#多表达式参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个方法签名,该方法签名使用来具有各种类型的多个属性

I'm trying to create a method signature that takes multiple properties of various type using

我会这样称呼它:

AllPropertiesExcept(() => Property1, () => Property2)

除了属性的类型必须相同之外,该方法几乎可以工作.我将只使用属性名称,但想使用lambda表达式来实现轻松的重构.

This method almost work, except that the type of the properties have to be the same. I'm only going to use the property name, but want to use lambda expression to enable easy refactoring.

public static string MyMethod<T>(params Expression<Func<T>>[] propertyExpression)

推荐答案

我会使用 AllPropertiesExcept(params Expression< Func< object>> []属性),仍然可以获取属性名称可以,但是属性的类型无关紧要.

I would use AllPropertiesExcept(params Expression<Func<object>>[] properties), you can still get the property names out of it, but it doesn't matter what type the property is.

但是,我倾向于以另一种方式使用它-而不是排除我不想看到的属性,而是包括我想看到的属性.原因很简单-为了使您的方式可行,您仍然需要反思-用我的方式,您可以轻松地使用获得的 Func 直接获取实际数据.

However, I would tend to use it the other way round - instead of excluding properties I don't want to see, I would include properties I want to see. The reason is simple - to make your way work, you still need reflection - with my way, you could easily use the Func you get to get the actual data directly.

编辑2(从表达式中获取属性名称):

Edit 2 (getting the property name out of an expression):

Expression<Func<object>> obj = something; // you get this in your method

((obj.Body as UnaryExpression).Operand as MemberExpression).Member.Name

我真的建议您使用LinqPad进行此类操作,您可以轻松地通过 Dump()向下钻取对象,该对象显示出非常用户友好的对象.只需重新创建一个小示例并进行实验.

I can really advise you to use LinqPad for such things, you can easily drill down objects via Dump(), which displays the objects very user friendly. Just recreate a small example and experiment.

这篇关于C#多表达式参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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