2011-11-21 64 views
2
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; } 

} 

如何轻松遍历所有这些并将它们设置为false?C#循环并设置结构中的所有字段

+6

不知道它可以帮助你,但默认情况下,他们都是假的。 –

+0

这是来自第三方库,所以不幸的是我不得不使用这个实现:/ – bulltorious

+1

而不是像某些人会建议的那样使用反射,只是创建一个新方法来将它们全部设置为false并咬住子弹。你特别要求一个循环,所以这不是一个答案......只是一个建议。 – SQLMason

回答

0

与反思:

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

默认情况下,布尔值为false。

你可以通过反射迭代属性,但这不会很快,但也许可以接受。

但也许想想那个。当你的对象的某些属性设置为true并且想将它们重置为false时,只需创建新对象。

3

您确定建模/表示是否正确?你有什么看起来不太正确。

考虑一下:

class Speaker 
{ 
    // not really relevant here 
    public SpeakerPosition Position {get; set;} //enum   

    public void PowerOff() { ... } 
} 

然后你使用它像这样:

class SpeakerSystem 
{ 
    Speaker[] _speakers = ...; 

    public void PowerOff() 
    { 
     foreach(var speaker in _speakers) 
      speaker.PowerOff(); 
    } 
} 
1

您可以使用Type.GetFields()Type.GetProperties(),使用反射,得到的值,SetValue设定值。

但是,为什么你不使用这个类?你确定你需要一个结构?

0

您的设计不起作用。

  • 在创建结构的所有值都默认设置它们是假的。
  • 的结构后创造的价值不能被改变

你有2种选择:

  • 变化的一类
  • 创建一个新的结构,当你需要重新设置该值
5

将全部设置为false相对容易,因为default(T)new T()将它们全部设为false。所以,你只需要到指定的默认值你感兴趣的变量。

speakers=default(Speakers); 

如果您需要一个非默认值,你可以使用反射,但它是一个有点难看,因为拳击将隐式复制您值。要设定所有的值设置为true,您可以:

Speakers speakers = new Speakers(); 
object boxedSpeakers = speakers; 
foreach(PropertyInfo p in sp.GetType().GetProperties()) 
    p.SetValue(boxedSpeakers, true, null); 
speakers = (Speakers)boxedSpeakers; 

你也可以考虑做一个更清洁的包装在第三方库从而从这个比较难看stuct隔离你的代码。

+0

+1除其他外,为解释:-) –