C# TryValidateProperty不能与泛型函数一起使用

C# TryValidateProperty不能与泛型函数一起使用,c#,data-annotations,validation,C#,Data Annotations,Validation,更新: 当我执行单元测试项目,然后它将返回未处理的时此测试结果还包含一个内部异常,而不是“Assert.IsTrue失败。描述字段是必需的。”结果类似于(0通过,1失败,1总计),但如果我使用F11调试,我们根本不会得到任何异常 [TestMethod] [Asynchronous] [Description("Determines whether the selected or single property is valide using the validation

更新: 当我执行单元测试项目,然后它将返回未处理的此测试结果还包含一个内部异常,而不是“Assert.IsTrue失败。描述字段是必需的。”结果类似于(0通过,1失败,1总计),但如果我使用F11调试,我们根本不会得到任何异常

    [TestMethod]
    [Asynchronous]
    [Description("Determines whether the selected or single property is valide using the validation context or validate single properties.")]
    public void ValidateSigleWithDataAnnotation()
    {
        LookupsServices lookupsservices = new LookupsServices();
        Lookups lookups = new Lookups() { Description = "", LookupReference = 2, DisplayOrder = 50};
        lookupsservices.Lookups.Add(lookups);

        //THIS IS NOT WORKING
        string message = ValidateProperties.ValidateSingle(lookups, "Description");
        Assert.IsTrue(message.Equals(""), message);
        //THIS IS WORKING
        var results = new List<ValidationResult>();
        Validator.TryValidateProperty(lookups.Description , new ValidationContext(lookups, null, null) { MemberName = "Description" }, results);
        Assert.IsTrue(results.Count == 0, results[0].ToString());
    }
如果我在没有泛型方法的情况下进行验证,我会得到错误“描述字段是必需的”,但为什么不使用泛型方法得到相同的错误呢


请帮助我……

比较这两个电话:

// In the generic method
Validator.TryValidateProperty(
    typeof(T).GetProperty(PeropertyName).Name, 
    new ValidationContext(t, null, null) { MemberName =  PeropertyName},
    ValidationMessages);

// The working call
Validator.TryValidateProperty(
    lookups.Description,
    new ValidationContext(lookups, null, null) { MemberName = "Description" },
    results);
在第一种形式中,您要传递属性的名称,即“Description”。在第二种形式中,传递的是属性的值,即“”。要使第一个电话看起来像第二个,您需要:

typeof(T).GetProperty(PeropertyName).GetValue(t, null), 

我不完全清楚这是否是您想要的(我自己没有使用过
验证程序),但这可能是答案。

比较这两个调用:

// In the generic method
Validator.TryValidateProperty(
    typeof(T).GetProperty(PeropertyName).Name, 
    new ValidationContext(t, null, null) { MemberName =  PeropertyName},
    ValidationMessages);

// The working call
Validator.TryValidateProperty(
    lookups.Description,
    new ValidationContext(lookups, null, null) { MemberName = "Description" },
    results);
在第一种形式中,您要传递属性的名称,即“Description”。在第二种形式中,传递的是属性的值,即“”。要使第一个电话看起来像第二个,您需要:

typeof(T).GetProperty(PeropertyName).GetValue(t, null), 

我不完全清楚这是否是您想要的(我自己没有使用
验证器
),但这可能是答案。

“不工作”是一个非常模糊的描述。请说出您预期会发生什么,以及发生了什么。请将这些信息编辑到问题中,而不是在评论中。谢谢您的评论,根据您的评论,我更新了我的问题。“不工作”是一个非常模糊的描述。请说出您预期会发生什么,以及发生了什么。请将这些信息编辑到问题中,而不是在评论中。谢谢您的评论,根据您的评论,我更新了我的问题。