Skip to main content
 首页 » 编程设计

c#之为什么我的属性(property)不做检查

2024年02月06日15bjzhanghao

我的构造函数从表单中获取信息。 'name' 由 'aName' 寻址(来自构造函数),然后必须使用 prop 'NameCheck' 进行检查。但是如果我编译它,它会返回一个空字符串。有什么想法吗?

代码:

---- 类 ----

//Fields 
private List<Create> Characters; 
private string name; 
private int health; 
private int mSpeed; 
private Role role; 
private Speciality speciality; 
 
//Properties 
public string NameCheck 
{ 
    get { 
        return name; 
    } 
    set 
    { 
        if (string.IsNullOrEmpty(name)) 
        { 
            name = "Name not specified"; 
        } 
        else  
        { 
            name = value; 
        } 
    } 
} 
 
//Constructor 
 
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality) 
{ 
    this.name = aName; 
    this.health = aHealth; 
    this.mSpeed = aMSpeed; 
    this.role = aRole; 
    this.speciality = aSpeciality; 
 
    Characters = new List<Create>(); 
} 

---- 表格 ----

Create character = new Create(tbName.Text, health, mspeed, aLane, aSpecial); 
 
Characters.Add(character); 
 
cbSummary.Items.Add(character.ToString()); 

PS:cbSummary 是一个组合框。

编辑:

public override string ToString() 
{ 
    return "Name: " + NameCheck + " - Health: "  + health + " -  MovementSpeed: " + mSpeed + " - Role: " + role + " - Speciality: " + speciality; 
} 

请您参考如下方法:

您应该在构造函数中设置 this.NameCheck 而不是 this.name

public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality) 
{ 
    this.NameCheck = aName; 

您还应该检查 value 是否为空或是否为空,而不是在您的属性 setter 中检查 name

set 
{ 
    if (string.IsNullOrEmpty(value)) 
    {