Can I define properties in partial classes, then mark them with attributes in another partial class?

前端 未结 5 1210
野趣味
野趣味 2020-12-02 06:17

Is there a way I can have a generated code file like so:

public partial class A {
public string a {get; set;}
}

and then in another file:

5条回答
  •  甜味超标
    2020-12-02 06:56

    Not as such; the compiler will complain that the member is defined in multiple parts. However, as the use of custom attributes is reflective in nature, you could define a "metadata" class and use it to contain decorators.

    public class A
    {
       public string MyString;
    }
    
    public class AMeta
    {
       [TheAttribute("etc")]
       public object MyString;
    }
    
    ...
    
    var myA = new A();
    var metaType = Type.GetType(myA.GetType().Name + "Meta");
    var attributesOfMyString = metaType.GetMember("MyString").GetCustomAttributes();
    

提交回复
热议问题