有沒有辦法使一個枚舉值不可瀏覽組合框
或只是,不從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