有没有办法使枚举值在组合框中不可浏览?
或者只是不想从Enum.GetValues()回来??
public enum DomainTypes
{
[Browsable(true)]
Client = 1,
[Browsable(false)]
SecretClient = 2,
} 发布于 2011-06-21 01:48:37
对于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属性生成枚举列表。
发布于 2013-05-29 02:30:36
这是一个泛型方法(基于另一个我找不到的SO答案),你可以在任何枚举上调用它。顺便说一句,System.ComponentModel中已经定义了Browsable属性。例如:
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();
}
}发布于 2011-06-21 01:39:33
它确实不能在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");
}希望这能有所帮助。祝好运!
https://stackoverflow.com/questions/6415023
复制相似问题