我的第一種方法看起來像它會很好地工作,直到我有一個運行時錯誤,我不知道如何解決在var name = ((LCData)attributes[0]).Name;
有關索引超出範圍。實際上,我只是複製了我在Getting attributes of Enum's value找到的代碼,所以我並不是100%確定它實際上做了什麼。所以當下面的代碼不起作用時,我轉向另一個解決方案。類型安全的枚舉或屬性枚舉?
public enum Identification : ushort
{
[LCAttribute("IMG_BG01_Greens")]
BG01_Greens = 0,
[LCAttribute("Rabbit", "IMG_E01_Rabbit")]
ENEMY_E01_Rabbit = 2000,
}
public static class Enums
{
public static LCData GetInfo(Identification id)
{
var type = typeof(Identification);
var memInfo = type.GetMember(id.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(LCData), false);
var name = ((LCData)attributes[0]).Name;
var tex = ((LCData)attributes[0]).Texture;
LCData data;
data.Name = name;
data.Texture = tex;
return data;
}
}
public struct LCData
{
public string Name;
public string Texture;
public LCData(Identification id)
{
this = Enums.GetInfo(id);
}
}
public class LCAttribute : System.Attribute
{
private string _Name;
public string Name
{
get
{
return _Name;
}
}
private string _Texture;
public string Texture
{
get
{
return _Texture;
}
}
public LCAttribute(string texture)
{
_Texture = texture;
}
public LCAttribute(string name, string texture)
{
_Name = name;
_Texture = texture;
}
}
其次我嘗試了類型安全的方法。這有2個致命的缺點,我找不到解決方案:
1)我無法獲得循環操作的可用枚舉條目列表。
2)我無法通過id號獲得相應的enum條目。
public sealed class Identification
{
private readonly ushort _ID;
private readonly string _Name;
private readonly string _Tex;
public static readonly Identification BG01_Greens = new Identification(0, "IMG_BG01_Greens");
public static readonly Identification ENEMY_E01_Rabbit = new Identification(2000, "Rabbit", "IMG_E01_Rabbit");
private Identification(ushort id, string tex)
{
_ID = id;
_Tex = tex;
}
private Identification(ushort id, string name, string tex)
{
_ID = id;
_Name = name;
_Tex = tex;
}
public ushort ID { get { return _ID; } }
public string Name { get { return _Name; } }
public string Texture { get { return _Tex; } }
}
我應該如何繼續?爲什麼我的第一個解決方案不工作?
你爲什麼不使用「字典」?它是類型安全的,閃電般快速,你可以列舉它。 –
類似:[簡化枚舉及其關聯值](http://stackoverflow.com/questions/14392428/simplification-of-enum-and-its-associated-values)。雖然這不是基於屬性。 – Theraot