How can I use attributes on a property defined in the other half of a partial class?

半腔热情 提交于 2019-12-01 17:37:15

问题


I have an autogenerated class from importing a web service containing something like this (abbreviated):

[System.Runtime.Serialization.DataMemberAttribute()]
public System.DateTime StartDate 
{
    get 
    {
        return this.StartDateField;
    }
    set { /* implementation prop changed */ }
}

And I want to add an MVC format attribute to this member. So in another file containing the same partial class definition, I would like to do something like the following (which is illegal):

[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] 
public DateTime StartDate;

A partial method is of no use here because partial methods must be private, have void return type, must be a method etc etc.

How can I decorate this member?


回答1:


You could use MetadataType attribute like this:

[MetadataType(typeof(MyClass_Validation))]     
public partial class MyClass
{} 

public class MyClass_Validation     
{     
   [DisplayFormat(...)] 
   public DateTime StartDate { get; set; } 
}


来源:https://stackoverflow.com/questions/10174519/how-can-i-use-attributes-on-a-property-defined-in-the-other-half-of-a-partial-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!