Associate attribute with code generated property in .net

后端 未结 4 510
遥遥无期
遥遥无期 2020-12-28 08:28

I wish to set an attribute on a public property in .NET, however I do not have access to the explicit property itself, as this has been code generated in another file.

4条回答
  •  太阳男子
    2020-12-28 09:21

    This is a known nuisance; you simply can't add metadata to the generated members.

    There are 6 options here (in order of increasing effort):

    • if you own the attribute, make it possible to declare it against the class, for example: [ValidateNonEmpty("Name", "Name is required", ExecutionOrder = 1)] - then add multiple attributes to the partial class definition
    • use a virtual / interface / etc method to query this, rather than via attributes
    • sublass the generated type; override or re-declare the member, adding the metadata (really messy)
    • use a custom TypeDescriptionProvider to provide dynamic metadata (lots and lots of work) - assuming that the consumer respects TypeDescriptor; most binding-related consumers do, but for example, Expression (used by many LINQ providers) doesn't
    • change the code-generator / write your own
    • try to extend something like PostSharp to do the work (I haven't found a way to do this, but I've love to hear if you find a way!)

    I usually have success with the first option, unless it is a system-defined attribute ([DisplayName], etc). If [ValidateNonEmpty] is defined by dynamic data, then you might not be able to do this.

提交回复
热议问题