C#3.0中的C#可选属性(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; } 

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

谢谢。

您可以使用您定义的属性修饰这些属性,并将属性标记为可选。

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

您可能还想查看具有类似function的validation应用程序块 。

C#没有’可选’关键字,正如@Mitch Wheat所说,这是一种执行validation的可怕方式。

为什么不能在属性设置器中进行validation?

如果你想用属性标记道具而不是自己的validation代码,为什么不尝试validation框架呢?

http://www.codeplex.com/ValidationFramework