English 中文(简体)
2. 以更灵活的方式减少属性
原标题:Decorate properties with attributes in a more flexible manner

请允许我说,我有这些阶层。

public class BaseClass
{
  public int Id { get; set; }
}

以及

public class SomeClass : BaseClass
{
  ... more properties ...
}

基地地图集被认为在许多地方使用。

In my case I m using ASP.NET MVC 3 s EditorForModel to render Views, 以及 it s common to decorate properties with attributes such as [Display(Name = "Id"), Required]

But lets say I would want to decorate the properties of BaseClass in different ways for every class that inherits it. In SomeClass I may want to decorate Id with [Required] 以及 in OtherClass I might want to decorate it with [SomeCustomAttribute].

Is there a way to this?

能够做这样的事情是明智的:

public class SomeClass : BaseClass
{
  public SomeClass()
  {
    WithProperty(x => x.Id).AddAttribute(new RequiredAttribute());
    ...
  }

  ... more properties ...
}
最佳回答

贡献是静态元数据。 组件、单元、类型、成员、参数和回报值是C#(如系统)的第一流物体。 类型类别仅反映了一种类型的代表性。 如果财产具有可仲裁性,那么你就可以获得某种特性的证明,并改变其特性,但这种特性对属性产生了影响,因为它适用于该特性的类型。

问题回答

您可以宣布财产为虚拟财产,并在衍生物类别中予以推翻。 否决了特定类别特性和所有类别都适用的任何属性。

Be sure that attributes applied to base properties are not themselves decorated with the AttributeUsageAttribute with an Inherited value of false (the default is true). If an attribute s AttributeUsage specifies Inherited == false then an overriding property will not inherit the attribute. See the documentation for more information.

不可能将属性与个别物体的属性分开。 它是具体元数据类型。 如果你真的需要,你将不得不执行你自己处理具体情况的属性管理。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签