c# - 将真值传递给 boolean 值

标签 c# constructor boolean

我正在尝试学习 C#,并且正在学习一个使用 boolean 值的示例。对于我的生活,我无法弄清楚为什么程序没有注意到我正在尝试将 true 值传递给 boolean 值。这是 Form.cs 中的代码:

namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        HappyBirthday birthdayMessage = new HappyBirthday();
        string returnedMessage;

        birthdayMessage.PresentCount = 5;
        birthdayMessage.MyProperty = "Adam";
        birthdayMessage.hasParty = true;
        returnedMessage = birthdayMessage.MyProperty;

        MessageBox.Show(returnedMessage);

    }
}
}

这是我创建的类:

class HappyBirthday
{

//====================
//  CLASS VARIABLES
//====================
private int numberOfPresents;
private string birthdayMessage;
private bool birthdayParty;

//===========================
//  DEFAULT CONSTRUCTOR
//===========================
public HappyBirthday()
{
    numberOfPresents = 0;
    //birthdayParty = false;
}

//===========================
//      METHOD
//===========================
private string getMessage(string givenName)
{

    string theMessage;

    theMessage = "Happy Birthday " + givenName + "\n";
    theMessage += "Number of presents = ";
    theMessage += numberOfPresents.ToString() + "\n";

    if (birthdayParty == true)
    {
        theMessage += "Hope you enjoy the party!";
    }
    else
    {
        theMessage += "No party = sorry!";
    }

    return theMessage;
}

//================================
//      READ AND WRITE PROPERTY
//================================
public string MyProperty
{
    get { return birthdayMessage; }

    set { birthdayMessage = getMessage(value); }
}

//================================
//     WRITE-ONLY PROPERTY
//================================
public int PresentCount
{
    set { numberOfPresents = value; }
}

public bool hasParty
{
    set { birthdayParty = value; }
}

}

现在我将初始值设置为 false(即使我的理解是正确的,这应该是默认值),但是当我尝试将其设置为 true 时,程序无法识别它。我是否应该以不同于字符串或整数的方式传递 boolean 值?

最佳答案

您在设置 hasParty 之前设置了 MyProperty。每次轮询 MyProperty 时,都不会调用 getMessage()

关于c# - 将真值传递给 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458373/

相关文章:

java - 各种 boolean 类型之间的区别?

c# - ASP.NET MVC 路由表中没有路由与提供的值匹配

java - 如何在另一个方法中调用类内的构造函数

android - SQLiteOpenHelper 类对上下文参数做了什么?

C++构造函数理解

swift - 可以比较包含 boolean 值的元组。但是官方文件说没有

c# - ASP.NET MVC 路由 - Url.Action 发送查询字符串而不是路由值

c# - 如何从类中向 Datagridview 添加行?

c# - 测试 WCF 服务的最佳方法是什么?

perl - 被 perl 中一个非常简单的 if/else 语句弄糊涂了