问题描述
我希望在 .NET 中为公共属性设置属性,但是我无权访问显式属性本身,因为这是在另一个文件中生成的代码.
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.
我有这个字段:
public virtual string Name { get; set; }
我想设置这个:
[ValidateNonEmpty("Name is required", ExecutionOrder = 1)]
public virtual string Name { get; set; }
我的课程被标记为部分,但你不能有部分属性.我以为我对 MetadataType 类有所了解,这是 Dynamic Data 和 DataAnnotations 的一个新功能,但可惜我觉得它只能与 Dynamic Data 一起使用,这是真的吗?
My class is marked as partial, but you cannot have partial properties. I thought I was on to something with the MetadataType class which is a new feature of Dynamic Data and DataAnnotations, but alas I feel it can only be used with Dynamic Data, is this true?
引用:http://blogs.oosterkamp.nl/blogs/jowen/archive/2008/10/16/metadatatype-attribute.aspxhttp:///blogs.msdn.com/davidebb/archive/2008/06/16/dynamic-data-and-the-associated-metadata-class.aspx
有什么方法可以设置这个属性(甚至通过 web.config!)而不接触代码生成的类?
Is there any way I can set this attributes (even through web.config!) without touching the code generated class?
提前致谢,格雷厄姆
推荐答案
这是一个已知的麻烦;您根本无法将元数据添加到生成的成员中.
This is a known nuisance; you simply can't add metadata to the generated members.
这里有 6 个选项(按努力增加的顺序):
There are 6 options here (in order of increasing effort):
- 如果您拥有该属性,则可以针对类声明它,例如:
[ValidateNonEmpty("Name", "Name is required", ExecutionOrder = 1)]
- 然后添加部分类定义的多个属性 - 使用虚拟/接口/等方法来查询这个,而不是通过属性来查询
- 子类化生成的类型;覆盖或重新声明成员,添加元数据(真的很乱)
- 使用自定义
TypeDescriptionProvider
来提供动态元数据(大量工作) - 假设消费者尊重TypeDescriptor
;大多数与绑定相关的消费者都会这样做,但例如,Expression
(被许多 LINQ 提供程序使用)不会 - 更改代码生成器/编写自己的代码
- 尝试扩展 PostSharp 之类的东西来完成这项工作(我还没有找到方法,但我很想听听你是否找到方法!)
- 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 respectsTypeDescriptor
; 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!)
我通常会成功使用第一个选项,除非它是系统定义的属性([DisplayName]
等).如果 [ValidateNonEmpty]
是由动态数据定义的,那么您可能无法做到这一点.
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.
这篇关于将属性与 .net 中的代码生成属性相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!