Passing a type as a parameter to an attribute

I wrote some general deserialization mechanism that allows me to create objects from the binary file format used by the C ++ application.

To make things clean and easy to change, I created a class Fieldthat extends Attribute, builds with Field(int offset, string type, int length, int padding)and applies to the class attributes that I want to deserialize. Here's what it looks like:

[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 };

The call myClass.Decompile(pathToBinaryFile)will then retrieve data from the file by reading the correct types and sizes at the correct offsets.

However, I believe that passing a type name as a string is ugly.

Is it possible to convey a type in a more elegant and shorter way, and how?

Thank.

+5
4

typeof ( Type):

[Field(0x7C, typeof(float), 3)]
+5

: Type , , . typeof(int).

+3

Yes, the parameter must be of type Type, and then you can pass the type as follows:

[Field(0x7C, typeof(float), 3)]
public float[] BackgroundLightAngle = { 0.0f, 0.0f, 0.0f };
+2
source

I don’t think you need to put the type in the constructor of the attribute, you can get it from the field. See an example:

public class FieldAttribute : Attribute { }

class Data
{
    [Field]
    public int Num;

    [Field]
    public string Name;

    public decimal NonField;
}


class Deserializer
{
    public static void Deserialize(object data)
    {
        var fields = data.GetType().GetFields();
        foreach (var field in fields)
        {
            Type t = field.FieldType;
            FieldAttribute attr = field.GetCustomAttributes(false)
                                     .Where(x => x is FieldAttribute)
                                     .FirstOrDefault() as FieldAttribute;
            if (attr == null) return;
            //now you have the type and the attribute
            //and even the field with its value
        }
    }
}

+1
source

All Articles