C # passing a list of strongly typed property names

I am looking for a way to pass a list of strongly typed property names to a method, which I can then parse and get the properties that the caller is interested in. The reason I want to do this is to have one that only copies the fields that the user specifies. Right now, the method takes a list of strings for use with Getvalues ​​and gets the property methods in reflection, but I want to protect against refactoring properties and strings not updated by the developer.

I found this article here , but unfortunately it does not make a list. I can do something like:

public static void Copy(Expression<Func<TObject>> propertiesToCopy ) { } 

And then make a call

 PropertyCopier<List<string>>.Copy(() => data); 

But then I have to indicate how many properties the caller can have the following:

 public static void Copy(Expression<Func<TObject>> propertiesToCopy,Expression<Func<TObject>> propertiesToCopy2, Expression<Func<TObject>> propertiesToCopy3 ) { } 

This will allow you to use three properties. Is there anyway to add it to the list or Queryable <> to allow as many properties as the caller wants? I tried using Add to List and have an expression

Thank you in advance

Edit: I found several articles this evening that link to using the C # param keyword to accomplish this. Are there better or more efficient ways, or is this a better way to do this?

+4
source share
1 answer

Use the params keyword to define a method that takes a variable number of arguments:

 public static void PrintPropertyNames<T>(params Expression<Func<T, object>>[] properties) { foreach (var p in properties) { var expression = (MemberExpression)((UnaryExpression)p.Body).Operand; string memberName = expression.Member.Name; Console.WriteLine(memberName); } } 

For example, you can call the PrintPropertyNames method, passing two expressions:

 PrintPropertyNames<FileInfo>(f => f.Attributes, f => f.CreationTime); 

This example displays the following output to the console:

 Attributes CreationTime 
+8
source

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


All Articles