gpt4 book ai didi

c# - 将类属性作为参数传递

转载 作者:太空狗 更新时间:2023-10-29 21:29:50 24 4
gpt4 key购买 nike

我想将一个类属性(或 getter/setter,如果需要的话)传递给一个函数。

例如,我有一个包含大量 bool 标志的类数组。

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;
}
}

我可以编写一个方法,返回所有选定标志为真的 Flags 实例

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
}

我将使用什么来允许我将类属性作为参数传递,从而使我不必为 Flags 的每个 bool 属性编写一次此方法(在本例中是三次,一次用于 a, b和 c)?

我试图避免为 Flags 提供一个 bool 数组,以使生成的代码易于阅读。我正在编写一个供相对缺乏经验的编码人员使用的库。

谢谢

(如果这是对 Passing property as parameter in method 的欺骗,我深表歉意,我无法确定这是否是同一个问题)

最佳答案

你可以使用 Func<Flags, bool>作为参数:

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
}

然后你可以像这样使用它:

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

但是真的你不应该重新发明这个 - Linq 开箱即用(注意相似性):

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

两种解决方案都要求 a、b、c 是公开的(在这种情况下应该是公共(public)属性(property))

关于c# - 将类属性作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7569411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com