有没有办法使一个枚举值不可浏览组合框
或只是,不从Enum.GetValues()
回来?枚举值`Browsable(false)`
public enum DomainTypes
{
[Browsable(true)]
Client = 1,
[Browsable(false)]
SecretClient = 2,
}
有没有办法使一个枚举值不可浏览组合框
或只是,不从Enum.GetValues()
回来?枚举值`Browsable(false)`
public enum DomainTypes
{
[Browsable(true)]
Client = 1,
[Browsable(false)]
SecretClient = 2,
}
对于你用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
属性枚举的列表。
它真的不能在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");
}
希望这会有所帮助。祝你好运!
这是一个通用的方法(基于另一个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();
}
}
为什么不创建一个Wrapper来获取要显示的值? –
@路易斯:你应该回答这个问题。 ;) – Sung