[英]Passing enum at object construction and use its attributes + best way to represent a memory in C#
我需要一種方法來代表各種處理器的一些 memory 布局,並認為通過使用枚舉來提供這些信息可能是一個好主意。
請提出更好的方法,因為我不使用枚舉是最好的選擇。
現在我對給定處理器 ProcX 的枚舉如下:
public static class ProcX
{
public enum MemorySegments
{
[MemSize(0x500)]
[Description("M0 base address")]
M0 = 0x0000,
[MemSize(0x500)]
[Description("M1 base address")]
M1 = 0x0500
...
}
}
如上所述,這些定義中有很多,應該使用它們來實例化和分配 memory 段。
所以現在,如果您考慮以下 MemorySegment Class,請參閱我想根據在構造時傳遞給它的枚舉在構造函數中分配 memory:
public class MemorySegment
{
public uint BaseAddress;
public uint MemSize;
....
public MemorySegment(Enum segments, string segName)
{
BaseAddress = segments(segName).....??;
MemSize= segments(segName) .....?;
// Then allocate mem using these values
...
}
}
現在,如果我嘗試創建 M0 類型的段:
MemorySegment mySeg = new MemorySegment(new ProcX.MemorySegments(), "M0"); // I am passing "M0" here for this example only
在“MemorySegment”構造函數中,如何提取所需的枚舉字段。 IE。 對於 M0,我們應該能夠根據 num 提供的信息將 BaseAddress 設置為 0 並將 MemSize 設置為 0x500。
有關信息,這是我的枚舉屬性:
public class MemSizeAttribute : System.Attribute
{
private int _value;
public MemSizeAttribute(int value)
{
_value = value;
}
public int Value
{
get { return _value; }
}
}
public static class EnumExtension
{
public static int MemSize<T>(this T value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
MemSizeAttribute[] attributes = (MemSizeAttribute[])fi.GetCustomAttributes(typeof(MemSizeAttribute), false);
if (attributes.Length > 0)
return attributes[0].Value;
else
return 0;
}
public static string Description<T>(this T value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
最后,我怎樣才能一個一個地循環遍歷枚舉的每個元素? IE。 如果我想一一實例化此枚舉中列出的所有段(從循環內)。
“最好”總是主觀的; 將事物存儲為enum
是可以的,但是必須通過屬性查找所有內容是非常低效和分配的。 坦率地說,如果這是我,我會保持簡單:
public static class ProcX
{
public static class MemorySegments {
public static MemorySegment M0 {get;}
= new MemorySegment (500, "M0 base address", 0x0000);
public static MemorySegment M1 {get;}
= new MemorySegment (500, "M1 base address", 0x0500);
// ...
}
}
public sealed class MemorySegment {
public int Size {get; }
public string Description {get;}
public int BaseAddress {get;}
internal MemorySegment(int size, string description, int baseAddress) {
Size = size;
Description = description;
BaseAddress = baseAddress;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.