开发者

C# optional properties in C# 3.0 (2009)

开发者 https://www.devze.com 2022-12-11 01:42 出处:网络
I am wondering if C# supports optional properties as the following public class Person { public string Name { get; set;}

I am wondering if C# supports optional properties as the following

public class Person
{
    public string Name { get; set;}
    public optional string 开发者_如何学编程NickName { get; set;}
    ...many more properties...
}

so that when I create a Person object I can easily check the validity of input values in a simple loop

public bool IsInputOK(Person person)
{
    foreach( var property in person.GetType().GetProperties())
    {
        if( property.IsOptional())
        {
             continue;
        }
        if(string.IsNullOrEmpty((string)property.GetValue(person,null)))
        {
             return false;
        }
    }
    return true;
 }

I have searched on google but didn't get desired solution. Do I really have to hand code validation code for each property manually?

Thanks.


You can decorate these properties with attribute you define and mark the properties as optional.

[AttributeUsage(AttributeTargets.Property,
                Inherited = false,
                AllowMultiple = false)]
internal sealed class OptionalAttribute : Attribute
{
}

public class Person
{
    public string Name { get; set; }

    [Optional]
    public string NickName { get; set; }
}

public class Verifier
{
    public bool IsInputOK(Person person)
    {
        foreach (var property in person.GetType().GetProperties())
        {
            if (property.IsDefined(typeof(OptionalAttribute), true))
            {
                continue;
            }
            if (string.IsNullOrEmpty((string)property.GetValue(person, null)))
            {
                return false;
            }
        }
        return true;
    }
}

You may also want to take a look at Validation Application Block which has similar capabilities out of the box.


C# does not have an 'optional' keyword, and as @Mitch Wheat says, it's a horrible way to perform validation.

Why can't you just do the validation in the properties setter?


if you want to tag the props with attributes and not roll your own validation code, why not try a validation framework?

http://www.codeplex.com/ValidationFramework

0

精彩评论

暂无评论...
验证码 换一张
取 消