C#循环并设置结构中的所有字段

bul*_*ous 2 c# types data-structures

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

}
Run Code Online (Sandbox Code Playgroud)

我怎样才能轻松遍历所有这些并将它们设置为false?

Cod*_*aos 5

将all设置为false相对容易,因为default(T)或者new T()全部都是false.所以你只需要将默认值分配给你感兴趣的变量.

speakers=default(Speakers);
Run Code Online (Sandbox Code Playgroud)

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

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

您还可以考虑在第三方库上创建一个更清晰的包装器,从而将代码与这个相当丑陋的结构隔离开来.