C#3.0中的C#可选属性(2009)

栏目: C# · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/1699772/c-sharp-optional-properties-in-c-sharp-3-0-2009

我想知道C#是否支持以下可选属性

public class Person
{
    public string Name { get; set;}
    public optional string NickName { get; set;}
    ...many more properties...
}

所以当我创建一个Person对象时,我可以在一个简单的循环中轻松检查输入值的有效性

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

我在谷歌搜索但没有得到理想的解决方案.我是否真的需要手动为每个属性处理代码验证代码?

谢谢.

您可以使用您定义的属性修饰这些属性,并将属性标记为可选.
[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;
    }
}

您可能还想看看具有类似功能的 Validation Application Block 开箱即用.

翻译自:https://stackoverflow.com/questions/1699772/c-sharp-optional-properties-in-c-sharp-3-0-2009


以上所述就是小编给大家介绍的《C#3.0中的C#可选属性(2009)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Agile Web Development with Rails 4

Agile Web Development with Rails 4

Sam Ruby、Dave Thomas、David Heinemeier Hansson / Pragmatic Bookshelf / 2013-10-11 / USD 43.95

Ruby on Rails helps you produce high-quality, beautiful-looking web applications quickly. You concentrate on creating the application, and Rails takes care of the details. Tens of thousands of deve......一起来看看 《Agile Web Development with Rails 4》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具