Passing a class property as a parameter

I would like to pass a class property (or, if necessary, getter / setter) a function reference.

For example, I have an array of a class with a lot of boolean flags.

class Flags { public bool a; public bool b; public bool c; public string name; public Flags(bool a, bool b, bool c, string name) { this.a = a; this.b = b; this.c = c; this.name = name; } } 

I can write a method that returns all flag instances for which the selected flag is true

 public Flags[] getAllWhereAisTrue(Flags[] array) { List<Flags> resultList = new List<Flags>(); for (int i = 0; i < array.Length; i++) { if (array[i].a == true) // for each Flags for which a is true { // add it to the results list resultList.Add(array[i]); } } return resultList.ToArray(); //return the results list as an array } 

What would I use to allow me to pass a class property as a parameter to save me from having to write this method once for each Boolean Flags property (in this example, three times, once for a, b and c)?

I am trying to avoid giving Flags an array of logic elements in an attempt to keep the resulting code easily readable. I am writing a library for use by relatively inexperienced coders.

thanks

(With an apology if this is a hoax Passing a property as a parameter in a method , I cannot say if this is the same problem)

+6
source share
2 answers

You can use the parameter Func<Flags, bool> as:

 public Flags[] getAllWhereAisTrue(Flags[] array, Func<Flags, bool> propertySelector) { List<Flags> resultList = new List<Flags>(); for (int i = 0; i < array.Length; i++) { if (propertySelector(array[i])) // for each Flags for which a is true { // add it to the results list resultList.Add(array[i]); } } return resultList.ToArray(); //return the results list as an array } 

Then you can use it as follows:

 var allAFlagsSet = getAllWhereAisTrue(flagsArray, x=> xa); 

But you should not really invent this - Linq does this out of the box (note the similarities):

 var allAFlagsSet = flagsArray.Where(x=> xa).ToArray(); 

Both solutions require a, b, c to be publicly available (in this case it must be a public property)

+7
source

according to the language specification, it is impossible to pass properties as ref parameters. fooobar.com/questions/79904 / ... is on the same item. moreover, I will stop the SLaks comment: LINQ has a method that does just that.

0
source

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


All Articles