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

标签 c# .net properties setter

我的构造函数从表单中获取信息。 '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))
    {

关于c# - 为什么我的属性(property)不做检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049282/

相关文章:

c# - 使用 2 个 Get 方法重载 WebAPI Controller

c# - ComboBox 的 Editbox 部分被自动选中

c# - 字符串中的粗体文本

c# - 为某些 Action MVC 添加相同的 AuthorizeAttribute 时如何覆盖全局 AuthorizeAttribute?

c# - 属性名称不同时Automapper的使用

javascript - (reactjs) 获取子组件值

php - 如何访问具有整数或无效属性名称等名称的对象属性?

c# - 启用片段级一致性时忽略 XML 模式验证?

c# - 我可以持有同一后代的对象类型列表<>吗?

c# - 移植出队 - 添加从 C# 到 F# 的循环