开发者

Passing a class property as a parameter

开发者 https://www.devze.com 2023-04-08 05:42 出处:网络
I\'d like to pass a class property (or a getter/setter if need be) reference to a function. For example I have an array of a class with lots of boolean flags.

I'd like to pass a class property (or a getter/setter if need be) reference to a function.

For example I have an array of a class with lots 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 instances of Flags for which a chosen 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, so as to save me from having to write this method once for each boolean property of Flags (in this example that's three times, once for a, b and c)?

I'm trying to avoid giving Flags an array of Booleans in an attempt to keep the resulting code easy to read. I'm writing a library for use by relatively inexperienced coders.

Thank you

(With apologies if this is a dupe of Passing property as parameter in method, I can't quite tell if it's the same issue)


You could use a Func<Flags, bool> as parameter:

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 could use it like this:

var allAFlagsSet = getAllWhereAisTrue(flagsArray, x=> x.a);

But really you should not reinvent this - Linq does this out of the box (notice the similarity):

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

Both solutions would require the a,b,c to be public (should really be a public property in this case)


according to the language spec it is not possible to pass properties as ref parameters. this stackoverflow post is on the same subject. moreover, I'll second the comment of SLaks: LINQ has a method that does just this.

0

精彩评论

暂无评论...
验证码 换一张
取 消