簡體   English   中英

如何使用兩個屬性值之一獲取枚舉值

[英]How to get an enum value with either one of two attribute values

編輯:我更新了帖子以使用Guid而不是int 感謝下面那些指出使用int沒有任何作用的人,因為枚舉的基本類型是int

我有一個枚舉,假設它是

public enum AnimalType
{
    [Animal("00000000000000000000000000000001")]
    Bear = 0,

    [Animal("00000000000000000000000000000002")]
    Cat = 1,

    [Animal("00000000000000000000000000000003")]
    Dog = 2
}

此枚舉使用 Animal 屬性,定義為:

public class AnimalAttribute : Attribute
{
    public AnimalAttribute(Guid id)
    {
        this.AnimalId = id;
    }

    public AnimalAttribute(string id)
    {
        this.AnimalId = new Guid(id);
    }

    public Guid AnimalId { get; private set; }

    // Some more properties

}

如您所見, AnimalAttribute有兩個構造AnimalAttribute ,允許將 id 作為stringGuid接受。 AnimalType枚舉使用string構造函數。

所以到目前為止,只能通過知道 id 來訪問枚舉值。 假設我不知道與特定枚舉值對應的 id,我還可以使用與每個枚舉值相對應的一些名稱/描述(可能只是 Bear 等的“Bear”)來訪問枚舉值。 我的問題是,如何設置它以便AnimalAttribute可以接受 id(以及作為字符串或 Guid)或與枚舉值對應的名稱/描述? 我想為AnimalAttribute制作另一個構造函數, AnimalAttribute所示:

public AnimalAttribute(string name)
{
    this.AnimalName = name; // assume there is an AnimalName property.
}

然后我可以為每個枚舉值添加另一個屬性,如下所示:

[Animal("00000000000000000000000000000001")]
[Animal("Bear")]
Bear = 0,

所以我可以提供任何一個值,我將能夠獲得枚舉值。 問題是我不能讓AnimalAttribute的構造AnimalAttribute接受string name因為已經有另一個構造函數接受string id 如果我不能這樣做,那么我想我可以使用可選參數制作構造函數。 有沒有簡單的方法來設置它?

不確定你的目標是什么,但你可能把它復雜化了。 使用具有int值的枚舉然后定義具有不同int值的屬性是沒有意義的。

看看使用 DescriptionAttribute 代替。 它是內置的,可以滿足您的需求。

查看獲取枚舉值的屬性

如果我誤解了你的場景的一些細節,請原諒我,但如果 Animal 屬性的 AnimalId 屬性總是等於 Enum 元素的 int 值,那么 Animal 屬性不是不必要的嗎? 你不能只做以下事情:

枚舉:

public enum AnimalType
{
    Bear = 0,
    Cat = 1,
    Dog = 2
}

要獲得 int 值,只需轉換枚舉:

int animalVal = (int)AnimalType.Bear;

要按值獲取動物名稱:

string animalName = Enum.GetName(typeof(AnimalType), 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM