-->

我怎么能在一个局部类的另一半定义的属性使用属性?(How can I use attributes

2019-06-23 16:19发布

我从导入包含这样的事情(略)Web服务的自动生成的类:

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

我想一个MVC格式属性添加到该成员。 因此,在包含相同的另一个文件partial class定义,我想这样做以下(这是非法的):

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

分部方法在这里没有用的,因为分部方法必须是私有的,必须返回void类型,必须是一个方法等等等等。

我怎样才能装点这位成员吗?

Answer 1:

你可以使用MetadataType属性是这样的:

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

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


文章来源: How can I use attributes on a property defined in the other half of a partial class?