验证对象状态时,ValidationResult类是否合适?

时间:2016-03-31 10:37:37

标签: c# winforms validation

我有一个C#WinForms应用程序,在每个对象中调用函数之前,集合中的多个对象需要有效。

我做了一些研究,并且有一个ValidationResult类。此类是否适合返回有关对象的验证数据,例如某些属性为null,还是应该使用另一个特定的类?

1 个答案:

答案 0 :(得分:1)

您可以使用RequiredAttribute命名空间中的System.ComponentModel.DataAnnotations。将此属性放在属性的顶部,以验证它是否为空,如下所示:

using System.ComponentModel.DataAnnotations;
public class MyDto
{
    [Required]
    public SomeObject SomeProperty { get; set; }
}

同样,您可以使用此命名空间中的more validation attributes

如果从ValidationAttribute继承,也可以创建自己的验证属性。例如,Validation属性验证列表中的每个对象,如:

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class ValidateCollectionAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var collection = value as IEnumerable;

            if (collection != null)
            {
                foreach (object element in collection)
                {
                    //do validation
                }
            }

            return ValidationResult.Success;
        }
    }

接下来,您可以使用Validator类来验证您的对象。您需要创建一个ValidationContext,将实例放入其中,如下所示:

var instance = new MyDto { SomeProperty = null }; //note that I'm setting the property to null, while the property has the Required attribute
var context = new ValidationContext(instance);
var validationResults = new List<ValidationResult>(); //this list will contain all validation results
Validator.TryValidateObject(instance, context, validationResults, validateAllProperties: true);
var errors = validationResults.Where(r => r != ValidationResult.Success); //filter out all successful results since we are only interested in errors
if (errors.Any())
{
    //do whatever you like to do
}

由于我已为MyDto null对象设置了Validator对象,因此ValidationResult将返回Required"siteMaster": [ { "sitename": "HTS_SITE_001", "sitelink": "http://facebook.com", "address" : "19/2, Bellandur, Bangalore India", "filename": "site1.json", "persons": 1, "status": "70%", "contact": "max.smith@honeywell.com", }, { "sitename": "HTS_SITE_002", "sitelink": "http://facebook.com", "address": "5th Avenue, New York", "filename": "site2.json", "persons": 1, "status": "70%", "contact": "john.smith@facebook.com", }, { "sitename": "HTS_SITE_003", "sitelink": "http://facebook.com", "address": "Palo Alto, California", "filename": "site3.json", "persons": 1, "status": "80%", "contact": "steve.jobs@apple.com", }, { "sitename": "HTS_SITE_004", "sitelink": "http://facebook.com", "address": "Bellandur, Bangalore", "filename": "site4.json", "persons": 1, "status": "80%", "contact": "max.mustermann@deutsche.com", } ] myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish'] wordtoFind = ['@Arsenal'] 属性触发。

您可以创建一个执行此类代码的服务,或者您可以在代码隐藏中硬连接它。无论你的船是什么漂浮。