Passing a type as parameter to an attribute

二次信任 提交于 2019-12-05 04:09:46

Use the typeof operator (returns an instance of Type):

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

Yes: make the attribute take a Type as a parameter, and then pass e.g. typeof(int).

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

I don't think you need to put the type in the constructor of the attribute, you can get it from the field. See the 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
        }
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!