クラスの一部のプロパティに値が含まれているか、範囲内にあることを確認する簡単な方法が必要でした(長さは50文字以下)。私はHow to validate Class properties?の質問と回答を使用しましたが残念ながら私はそれを動作させることができませんでした。クラスプロパティの必須フィールドを検証する方法は?
これをテストするために、私は非常に単純なWinFormのサンプルをC#で作成しました。私はすべて同じことをしていますが、間違った値を適用すると(つまり、許容限度を超えて年齢を設定するなど)、検証例外が発生することはありません。
誰かが例外をスローしない理由を説明できますか?クラスが必要な属性を使用するはずであることをクラスが知らないかのようです。
のForm1.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel.DataAnnotations;
namespace RequiredFieldsInClassExample {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void btnTest_Click(object sender, EventArgs e) {
try {
lstStatus.Items.Clear();
lstStatus.Items.Add("Creating list of people");
List<Person> CollectionOfPeople = new List<Person>();
lstStatus.Items.Add("Creating a good person");
Person Jeff = new Person();
Jeff.Age = 33;
Jeff.Firstname = "Jeff";
Jeff.Lastname = "Jefferson";
Jeff.GroupCode = "JJJ";
CollectionOfPeople.Add(Jeff);
lstStatus.Items.Add("Creating a bad person");
Person Tim = new Person();
Tim.Age = 444;
Tim.Firstname = "";
Tim.Lastname = "";
Tim.GroupCode = "";
CollectionOfPeople.Add(Tim);
lstStatus.Items.Add("Done");
} catch (ValidationException Exp) {
MessageBox.Show(this, Exp.Message, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
} catch (Exception Exp) {
MessageBox.Show(this, Exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
Person.csは
using System.ComponentModel.DataAnnotations;
public class Person {
private int m_iAge = 1;
private string m_sFirstname = "Unknown";
private string m_sLastname = "";
private string m_sGroupCode = "AAA";
//[Required(ErrorMessage = "Age is a required field.")]
//[Range(1, 100, ErrorMessage = "A persons age must be between 1 and 100.")]
[Required, Range(1, 100)]
public int Age
{
get { return m_iAge; }
set { m_iAge = value; }
}
//[Required(ErrorMessage = "Firstname is a required field.")]
[Required]
public string Firstname
{
get { return m_sFirstname; }
set { m_sFirstname = value; }
}
public string Lastname
{
get { return m_sLastname; }
set { m_sLastname = value; }
}
//[StringLength(3)]
public string GroupCode
{
get { return m_sGroupCode; }
set { m_sGroupCode = value; }
}
}
それは値を設定するとプロパティを検証するつもりはない、あなたが持っている(http://odetocode.com/blogs/scott/archive/2011/ 06/29/manual-validation-with-data-annotations.aspx)。 – Michael
@Michael - あなたのリンクに問題解決のための情報が含まれているので、あなたは答えを作成できますか? – ThePeter
あなた自身の回答を投稿し、遅れてそれを自己承諾することもできます。これは、将来の読者に役立つ質問に答えたものをマークします。 – Tim