简体   繁体   中英

C# Passing / retrieving a property name from a parameter without reflection

I want to pass a property to a function such that the function knows both the value of the property and the name of the property. This is so I can return errors that match the property names.

I currently have code like this:

var userNameField = personField.GetChildField(f => f.UserName, nameof(personField.Value.UserName));

many times repeated, so the 2nd parameter is the name of the property inside the lambda of the 1st parameter.

Is it possible to automate this parameter so:

  1. The duplicate code is gone
  2. The string name of the property is calculated at compile-time, not run-time for every call

Ideally I would like my code to simply look like:

var userNameField = personField.GetChildField(f => f.UserName);

I have got this working using reflection using Expression<Func... ie ((MemberExpression) getPropertyFunc.Body).Member.Name; but this is too slow, in particular compiling the expression into a function which I can use to fetch the property value.

Similarly, I have read through the ideas here: Get name of property as a string

Is there any way of populating the property name from the GetChildField function at compile time? Or encoding it into the model somehow?

It is possible by following:

Item model=new Item();    
var propertyInfo = model.GetType();    
var value=propertyInfo.GetProperty("IrrA").GetValue(model, null).ToString();

According to the Roslyn documentation found here the nameof operator is evaluated at compile-time per the first line under the "Semantics" section that reads

The nameof expression is a constant. In all cases, nameof(...) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an "unreachable code" warning).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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