C # multiple expression options

I am trying to create a method signature that uses several properties of various types using

I would call it something like this:

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

This method almost works, except that the type of properties must be the same. I will use the property name, but I want to use a lambda expression to simplify refactoring.

public static string MyMethod<T>(params Expression<Func<T>>[] propertyExpression)
+3
source share
3 answers

I would use AllPropertiesExcept(params Expression<Func<object>>[] properties), you can still get property names from it, but no matter what type the property has.

: , - , , , . : , - Func, .

2 ( ):

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

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

LinqPad , Dump(), , . .

+3

AllPropertiesExcept() -? ( ):

AllPropertiesExcept(() => Property1)
    .And(() => Property2)
    .And(() => Property3);

AllPropertiesExcept() -, :

var foo = AllPropertiesExcept(() => Property1)
    .And(() => Property2)
    .And(() => Property3)
    .DoSomeThing();
+2

, ModelMetadata, : http://msdn.microsoft.com/en-us/library/system.web.mvc.modelmetadata.aspx

This class is used in ASP.NET MVC in situations such as Html.LabelFor (x → x.Name). The expression is passed to the ModelMetadata.FromLambdaExpression method described here: http://msdn.microsoft.com/en-us/library/ee428393 .aspx

Once you understand how it is used in MVC, you can create your own code with some knowledge of how it has been applied elsewhere.

0
source

Source: https://habr.com/ru/post/1793938/


All Articles