枚举值 `Browsable(false)`

4
有没有办法使枚举值不能在组合框中浏览?或者说,在Enum.GetValues()返回时不要出现?
public enum DomainTypes  
{  
    [Browsable(true)]  
     Client = 1,  
    [Browsable(false)]  
    SecretClient = 2,    
} 

4
为什么不创建一个包装器来获取您想要显示的值? - Luis Filipe
1
@Luis:你应该用问题回答这个问题。;) - dance2die
3个回答

5

这是一个通用的方法(基于另一个我找不到的SO答案),您可以在任何枚举上调用它。 顺便说一下,Browsable属性已经在System.ComponentModel中定义了。 例如:

ComboBox.DataSource = EnumList.Of<DomainTypes>();

...

public class EnumList
{
    public static List<T> Of<T>()
    {
        return Enum.GetValues(typeof(T))
            .Cast<T>()
            .Where(x => 
                {
                    BrowsableAttribute attribute = typeof(T)
                        .GetField(Enum.GetName(typeof(T), x))
                        .GetCustomAttributes(typeof(BrowsableAttribute),false)
                        .FirstOrDefault() as BrowsableAttribute;
                    return attribute == null || attribute.Browsable == true;
                }
            )
        .ToList();
    }
}

1

在C#中真的做不到 - 公共枚举会暴露所有成员。相反,考虑使用包装类来有选择地隐藏/暴露项目。也许可以像这样:

public sealed class EnumWrapper
{
    private int _value;
    private string _name;

    private EnumWrapper(int value, string name)
    {
        _value = value;
        _name = name;
    }

    public override string ToString()
    {
        return _name;
    }

    // Allow visibility to only the items you want to
    public static EnumWrapper Client = new EnumWrapper(0, "Client");
    public static EnumWrapper AnotherClient= new EnumWrapper(1, "AnotherClient");

    // The internal keyword makes it only visible internally
    internal static readonly EnumWrapper SecretClient= new EnumWrapper(-1, "SecretClient");
}

希望这能有所帮助。祝你好运!


1

使用 Enum.GetValues() 方法并没有现成的方法来实现这个功能。如果你想要使用属性,你可以创建自己的自定义属性,并通过反射来使用它:

public class BrowsableAttribute : Attribute
{
  public bool IsBrowsable { get; protected set; }
  public BrowsableAttribute(bool isBrowsable)
  {
    this.IsBrowsable = isBrowsable;
  }
}

public enum DomainTypes  
{  
    [Browsable(true)]  
     Client = 1,  
    [Browsable(false)]  
    SecretClient = 2,    
} 

然后你可以使用反射来检查自定义属性,并根据 Browsable 属性生成一个枚举列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接