Windows窗体,Set方法引发string.isnullorempty异常?C#
这是一个包含名字和姓氏值的类。 另一个名为attendee的课程是从person开始的Windows窗体,Set方法引发string.isnullorempty异常?C#,c#,winforms,C#,Winforms,这是一个包含名字和姓氏值的类。 另一个名为attendee的课程是从person开始的 class Person { static private string FirstName; static private string LastName; static public string firstname { get {
class Person
{
static private string FirstName;
static private string LastName;
static public string firstname
{
get
{
return FirstName;
}
set
{
if(string.IsNullOrEmpty(FirstName))
{
throw new ArgumentException("First name must not be blank!");
}
FirstName = value;
}
}
这在我的GUI类中,该方法检索名字的值并在Person类中更新它
private void BtnSet_Click(object sender, EventArgs e)
{
Attendee.firstname = FirstName.Text;
... //more code (not relevant)
}
出于某种原因,这会引发Person类的异常,但我不明白为什么?如果在
FirstName
属性的setter中检查最初为空的FirstName
字段,请改用
set
{
if(string.IsNullOrEmpty(value))
{
throw new ArgumentException("First name must not be blank!");
}
FirstName = value;
}
在
FirstName
属性的setter中,检查最初为空的FirstName
字段,改用
set
{
if(string.IsNullOrEmpty(value))
{
throw new ArgumentException("First name must not be blank!");
}
FirstName = value;
}
到目前为止工作得很好!谢谢。值不应该是小写的吗?到目前为止还可以!谢谢。值不应该是小写的吗?您将FirstName声明为静态成员,因此您对FirstName的引用。Text查找静态FirstName并获取其不存在的Text属性,因此出现异常。是否需要静态类?还是你这么做是为了让代码“工作”?在包含异常的代码中,是否需要Textbox的Text属性?它的名字可能不是名字;-)您将FirstName声明为静态成员,因此您对FirstName的引用。Text查找静态FirstName并获取其不存在的Text属性,因此出现异常。是否需要静态类?还是你这么做是为了让代码“工作”?在包含异常的代码中,是否需要Textbox的Text属性?它的名字可能不是名字;-)