我正在使用VS 2010 RTM并尝试使用MetadataTypeAttribute对简单类型执行一些基本验证。当我把验证属性放在主类上时,一切正常。但是,当我把它放在元数据类上时,它似乎被忽略了。我一定会错过一些微不足道的东西,但我现在一直在困扰着这个问题。使用验证程序时忽略.NET 4 RTM MetadataType属性
我看过企业库验证块作为解决方法,但它不支持验证开箱即用的单个属性。有任何想法吗?
class Program
{
static void Main(string[] args)
{
Stuff t = new Stuff();
try
{
Validator.ValidateProperty(t.X, new ValidationContext(t, null, null) { MemberName = "X" });
Console.WriteLine("Failed!");
}
catch (ValidationException)
{
Console.WriteLine("Succeeded!");
}
}
}
[MetadataType(typeof(StuffMetadata))]
public class Stuff
{
//[Required] //works here
public string X { get; set; }
}
public class StuffMetadata
{
[Required] //no effect here
public string X { get; set; }
}
感谢您的代码! – aikeru 2012-08-23 17:33:16
为什么在MSDN的MetadataTypeAttribute列表中没有注明这一点?我已经挂了几个小时b/c在我的MVC项目一切工作正常,但是当创建我的Windows应用程序时,我需要解释 – 2015-11-03 17:37:20