我希望在 .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 提供程序使用)不会[ValidateNonEmpty("Name", "Name is required", ExecutionOrder = 1)]
- then add multiple attributes to the partial class definitionTypeDescriptionProvider
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我通常会成功使用第一个选项,除非它是系统定义的属性([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 中的代码生成属性相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!