Custom Attributes on Class Members

后端 未结 2 1866
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 12:20

I am using a Custom Attribute to define how a class\'s members are mapped to properties for posting as a form post (Payment Gateway). I have the custom attribute working ju

2条回答
  •  灰色年华
    2020-12-30 13:17

    You can do half of it a bit more simply:

        foreach (PropertyMapping attrib in
            Attribute.GetCustomAttributes(i, typeof(PropertyMapping)))
        {
            ret += map.FieldName; // whatever you want this to do...
        }
    

    btw; you should make a habit of ending attributes with the word Attribute. Even if this causes duplication (see [XmlAttributeAttribute]).

    However - re serialization; that isn't always trivial. A deceptive amount of code goes into serialization frameworks like Json.NET etc. The normal approach might be to get a type-converter, but in many ways this is easier with a PropertyDescriptor:

        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
        {
            Console.WriteLine("{0}={1}",
                prop.Name, prop.Converter.ConvertToInvariantString(
                    prop.GetValue(obj)));
        }
    

提交回复
热议问题