【问题标题】:Validation attributes验证属性
【发布时间】:2011-02-10 17:39:39
【问题描述】:

我有一个抽象类,它从某个接口继承了一个属性。所以不可能验证属性支持字段。那么您对如何实现自定义属性来验证属性有任何想法吗?

你有抽象类 Collaborator,

public abstract class Collaborator
{
}

然后你从一些接口继承它:

interface IPersonInformation
{
    String FirstName { get; set; }
    String LastName { get; set; }
}
interface IRecruitmentInformation
{
    DateTime RecruitmentDate { get; set; }
}
///
public abstract class Collaborator : IPersonInformation, IRecruitmentInformation
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public DateTime RecruitmentDate { get; set; } 
}

因此,您无法使用支持字段验证Collaborator 类中的属性 - 它们是自动的。 那么有没有办法使用属性上的属性来验证名称?

【问题讨论】:

  • 您的问题不清楚。能否提供示例代码?
  • 您不必使用自动实现的属性。无论如何,您都可以使用验证属性(PostSharp、ValidationManager)。

标签: c# validation custom-attributes


【解决方案1】:
public abstract class Collaborator : IPersonInformation, IRecruitmentInformation
{
    private string firstName;
    public String FirstName
    { 
        get { return firstName; }
        set 
        {

            //validation code

            this.firstName = value;
        }
    }
    public String LastName { get; set; }
    public DateTime RecruitmentDate { get; set; } 
}

作为实现接口的一种方式应该可以正常工作。我想不出更好的方法来使用属性来实现这一点。

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多