在C#3.0 C#可选属性(2009) [英] C# optional properties in C# 3.0 (2009)

查看:96
本文介绍了在C#3.0 C#可选属性(2009)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果C#支持可选的属性,以下

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...
}



所以,当我创建一个Person对象,我可以很容易地检查输入值的有效性在一个简单的循环

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?

感谢。

推荐答案

您可以装饰这些属性与您所定义的属性和标记属性为可选。

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;
    }
}

您可能还需要看一看<一个HREF =http://msdn.microsoft.com/en-us/library/cc309509.aspx>验证应用程序块的具有开箱即用的类似的功能。

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

这篇关于在C#3.0 C#可选属性(2009)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆