C#の属性を使ってオブジェクトのプロパティの単項目チェックを行います。
こういうのは多分フレームワークにあるとは思いますが、C#初級者なので記事にしておきます。
コードは「.Net Fiddle」というWeb IDEで確認しました。
基本はJavaのアノテーションとほぼ同じですが、C#はチェックされる例外がないのでリフレクションで取得してもコードはすっきりします。
DisplayNameとStringLength、Requiredという既存の属性を使用しています。
Attribute.GetCustomAttributメソッドで対象(今回はプロパティ)から属性を取得できます。
using System;
using System.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class Program
{
public static void Main()
{
Entity entity = new Entity(){Id = "123456", Name = ""};
validate(entity);
}
private static void validate(object obj)
{
foreach(PropertyInfo prop in obj.GetType().GetProperties())
{
// 値
string val = prop.GetValue(obj).ToString();
// DisplayName属性取得
DisplayNameAttribute dispNameAttr = Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute)) as DisplayNameAttribute;
// StringLength属性取得
StringLengthAttribute lenAttr = Attribute.GetCustomAttribute(prop, typeof(StringLengthAttribute)) as StringLengthAttribute;
// Required属性取得
RequiredAttribute reqAttr = Attribute.GetCustomAttribute(prop, typeof(RequiredAttribute)) as RequiredAttribute;
// ↓チェック処理
if (lenAttr != null && val.Length > lenAttr.MaximumLength)
{
Console.WriteLine(string.Format("{0}({1})は最大桁数{2}桁を超えています。", dispNameAttr.DisplayName, val, lenAttr.MaximumLength));
}
if (reqAttr != null && string.IsNullOrEmpty(val))
{
Console.WriteLine(string.Format("{0}は必須項目です。", dispNameAttr.DisplayName));
}
}
}
private class Entity
{
[DisplayName("ID")]
[StringLength(5)]
[Required]
public string Id {get;set;}
[DisplayName("なまえ")]
[StringLength(20)]
[Required]
public string Name {get;set;}
}
}
//ID(123456)は最大桁数5桁を超えています。
//なまえは必須項目です。