C# 4.0 验证类内的数据批注:TryValidateObject结果始终为空

C# 4.0 验证类内的数据批注:TryValidateObject结果始终为空,c#-4.0,data-annotations,C# 4.0,Data Annotations,我目前正在将.NET3.5代码迁移到.NET4.0,在那里我实现了自己的验证逻辑。使用数据注释来验证数据,似乎非常简单,我就是不能让它很难工作 下面是一个简单的例子,说明我正在努力实现的目标。 传递给TryValidateObject的结果集合的计数始终为0 我做错了什么 public class CreateBuskerMemberCommand : Command { [Required] public string SomeValue; public string So

我目前正在将.NET3.5代码迁移到.NET4.0,在那里我实现了自己的验证逻辑。使用数据注释来验证数据,似乎非常简单,我就是不能让它很难工作

下面是一个简单的例子,说明我正在努力实现的目标。 传递给TryValidateObject的结果集合的计数始终为0

我做错了什么

public class CreateBuskerMemberCommand : Command
{
   [Required]
   public string SomeValue;

   public string SomeOtherValue;

   public CreateBuskerMemberCommand ( ..)
   {
      // pass values to fields.. 
   }


   public void Execute()
   {

       // force error for testing purpose
       SomeValue = null;
       ValidationContext context = new ValidationContext(this, null, null);
       List<ValidationResult> results = new List<ValidationResult>();

       System.ComponentModel.DataAnnotations.Validator.TryValidateObject(this, context,   results);

      // results count = 0
   }
}
public类CreateBuskerMemberCommand:Command
{
[必需]
公共字符串值;
公共字符串SomeOtherValue;
公共CreateBuskerMemberCommand(..)
{
//将值传递给字段。。
}
public void Execute()
{
//测试用力误差
SomeValue=null;
ValidationContext=新的ValidationContext(this,null,null);
列表结果=新列表();
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(这个、上下文、结果);
//结果计数=0
}
}
非常简单的解决方案: 属性必须位于属性上,而不是字段上。这就成功了

   [Required]
   public string SomeValue {get;set;}