【发布时间】:2011-08-15 08:40:32
【问题描述】:
我编写了一种通用的反序列化机制,它允许我从 C++ 应用程序使用的二进制文件格式构造对象。
为了保持简洁和易于更改,我创建了一个扩展 Attribute 的 Field 类,使用 Field(int offset, string type, int length, int padding) 构造并应用于我希望反序列化的类属性。这就是它的样子:
[Field(0x04, "int")]
public int ID = 0;
[Field(0x08, "string", 0x48)]
public string Name = "0";
[Field(0x6C, "byte", 3)]
public byte[] Color = { 0, 0, 0 };
[Field(0x70, "int")]
public int BackgroundSoundEffect = 0;
[Field(0x74, "byte", 3)]
public byte[] BackgroundColor = { 0, 0, 0 };
[Field(0x78, "byte", 3)]
public byte[] BackgroundLightPower = { 0, 0, 0 };
[Field(0x7C, "float", 3)]
public float[] BackgroundLightAngle = { 0.0f, 0.0f, 0.0f };
然后调用myClass.Decompile(pathToBinaryFile) 将从文件中提取数据,在适当的偏移处读取适当的类型和大小。
但是,我发现将类型名称作为字符串传递是丑陋的。
是否可以以更优雅、更简短的方式传递 type,以及如何传递?
谢谢。
【问题讨论】:
-
类型和标记的字段一样,不是吗?为什么不从字段中获取类型,而不是在属性的构造函数中标记它?
标签: c# generics custom-attributes