C# 循环并设置结构中的所有字段
如何轻松地循环所有这些并将它们设置为false?默认情况下布尔值为false 您可以使用反射来迭代属性,但这不会很快,但对您来说可能是可以接受的C# 循环并设置结构中的所有字段,c#,data-structures,types,C#,Data Structures,Types,如何轻松地循环所有这些并将它们设置为false?默认情况下布尔值为false 您可以使用反射来迭代属性,但这不会很快,但对您来说可能是可以接受的 但也许你可以考虑一下。当对象的某些属性设置为true,并希望将其重置为false时,只需创建新对象。您确定建模/表示正确吗?你的东西看起来不太对劲 考虑这一点: public struct Speakers { //... public bool BackCenter { get; set; } public bool Ba
但也许你可以考虑一下。当对象的某些属性设置为true,并希望将其重置为false时,只需创建新对象。您确定建模/表示正确吗?你的东西看起来不太对劲 考虑这一点:
public struct Speakers
{
//...
public bool BackCenter { get; set; }
public bool BackLeft { get; set; }
public bool BackRight { get; set; }
public bool FrontCenter { get; set; }
public bool FrontLeft { get; set; }
public bool FrontLeftOfCenter { get; set; }
public bool FrontRight { get; set; }
public bool FrontRightOfCenter { get; set; }
public bool SideLeft { get; set; }
public bool SideRight { get; set; }
public bool Subwoofer { get; set; }
public bool TopBackCenter { get; set; }
public bool TopBackLeft { get; set; }
public bool TopBackRight { get; set; }
public bool TopCenter { get; set; }
public bool TopFrontCenter { get; set; }
public bool TopFrontLeft { get; set; }
public bool TopFrontRight { get; set; }
}
然后你就这样使用它:
class Speaker
{
// not really relevant here
public SpeakerPosition Position {get; set;} //enum
public void PowerOff() { ... }
}
您可以使用反射使用
Type.GetFields()
或Type.GetProperties()
来获取值,并使用SetValue
来设置值
但是,为什么不为此使用类呢?你绝对确定你需要一个结构吗?你的设计将无法工作
- 创建结构时,默认情况下会设置所有值,这些值为false
- 创建结构后,无法更改值
- 换班
- 当需要重置值时,创建一个新结构
default(T)
或new T()
将它们全部设置为false
。因此,您只需要为感兴趣的变量指定默认值
class SpeakerSystem
{
Speaker[] _speakers = ...;
public void PowerOff()
{
foreach(var speaker in _speakers)
speaker.PowerOff();
}
}
如果需要非默认值,可以使用反射,但这有点难看,因为装箱将隐式复制您的值。要将所有值设置为true,您可以:
speakers=default(Speakers);
你也可以考虑在第三方库上制作一个更干净的包装器,从而将你的代码与这个相当丑陋的代码隔离开来。
反省:
Speakers speakers = new Speakers();
object boxedSpeakers = speakers;
foreach(PropertyInfo p in sp.GetType().GetProperties())
p.SetValue(boxedSpeakers, true, null);
speakers = (Speakers)boxedSpeakers;
对象a=新扬声器();//必须装箱,否则无法更改结构
PropertyInfo[]信息=a.GetType().GetProperties();
对于(int i=0;i
不知道这对您有什么帮助,但默认情况下它们都是false。这是来自第三方库的,因此不幸的是,我被迫使用了此实现:/。你特别要求循环,所以这不是答案。。。只是一个建议。首先不要这样做。结构应该是小的且逻辑上不可变的值。您所描述的数据结构是大的、可变的;这应该是一门课。你到底为什么要把这东西变成一个结构?再说一遍。这是我正在使用的第三方库,因此有些设计决策是在没有我的情况下做出的。
object a = new Speakers(); // required boxing, otherwise you cannot change a struct
PropertyInfo[] info = a.GetType().GetProperties();
for (int i = 0; i < info.Length; i++)
{
info[i].SetValue(a, false, null);
}