【问题标题】:How to make conditions with IF statement right?如何用 IF 语句创建条件?
【发布时间】:2022-01-18 11:49:24
【问题描述】:

我对我的 IF 语句有疑问,它不起作用 :D 我想检查 ID、年龄和薪水,如果它大于 0,但我的代码只是忽略了这一点,想将 0 更改为某些含义,例如 - if age

class Person
{
    private int _age;
    private string _firstName;
    private string _lastName;
    private int _id;

    public Person(int age, string firstName, string lastName, int id)
    {
        _age = age;
        _firstName = firstName;
        _lastName = lastName;
        _id = id;
    }    
    
    public int GetAge()
    {
        return _age;
    }
    public void SetAge(int age)
    {
        if (_age == 0)
            _age = 21;
        else
            _age = age;
    }
    public int GetId()
    {
        return _id;
    }
    public void SetId(int id)
    {
        if (id > 0)
            _id = id;
        else
            _id = 1;
        
    }
    public void Print()
    {
        Console.WriteLine("Age: {0}\tFirst name: {1}\tLast name: {2}\tID: {3}", this._age, this._firstName, this._lastName, this._id);
    }
}

class TestInheritence
{
    public static void Main(string[] args)
    {
        Employe[] employees = new[]
        {
            new Employe(21, "John", "Watson", 0)
        };
        employees[0].Print();
    }  
}

【问题讨论】:

  • 顺便说一下,“Get*”和“Set*”方法是Java语法。在 C# 中,您将使用 properties
  • 你为 id 做对了,为年龄复制该模式
  • @CaiusJard 但它也不起作用:D

标签: c# visual-studio if-statement


【解决方案1】:

这里有一个错误:

public void SetAge(int age)
{
    if (_age == 0)  //<-- This should be age==0, not _age
        _age = 21;
    else
        _age = age;
}

您可以从使用属性中受益。或者按照公认的答案建议实际使用您的 Set 方法。

【讨论】:

  • 问题正文说
  • 我现在已经写了那个jsut但是它不起作用,也许我还有一个错误?
【解决方案2】:

这是因为您不使用具有 if 语句的 setter,而是直接设置变量。
所以不是

_age = age;

你应该使用

setAge(age);

【讨论】:

  • 我应该在这里使用它吗? public void SetAge(int age) { if (_age == 0) _age = 21;否则 _age = 年龄; }
  • @DaniilGalitskii 不,你应该在构造函数中使用它。
【解决方案3】:

尝试使用您在更新变量时编写的设置器,以便它到达代码中的条件语句。 此外,年龄的 if 语句应该是:if(age &lt;= 0) _age = 21;

【讨论】:

  • 但是结合@Kevin和PalleDue写的方法
猜你喜欢
  • 2023-02-03
  • 1970-01-01
  • 2016-02-28
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-23
相关资源
最近更新 更多