将true值传递给布尔值

use*_*778 4 c# constructor boolean

我正在尝试学习C#,我是一个使用布尔值的例子.对于我的生活,我无法弄清楚为什么程序没有注意到我试图将值传递给布尔值.这是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);

    }
}
}
Run Code Online (Sandbox Code Playgroud)

这是我创建的类:

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; }
}

}
Run Code Online (Sandbox Code Playgroud)

现在我将初始值设置为false(即使我的理解是正确的,应该是默认值),但是当我尝试设置it = true时,程序无法识别它.我应该以不同的方式传递布尔值,然后我会使用字符串或int吗?

小智 7

您在设置MyProperty之前进行了设置hasParty. getMessage()每次MyProperty轮询时都不会被调用.

  • 是的,这是正确的答案.此外,整个MyProperty的想法并不是一个好的实现.使用此类的函数应该能够将每个属性视为关联的字段或对象.如果您正在设置,MyProperty代表一个人的姓名,如果您正在设置,则代表生日消息.而是创建一个Name属性和一个消息属性.该消息将具有getter,但没有setter,并且getter使用您设置的Name值.如果没有设置名称,它可以给出不同的信息,比如"谁?" (2认同)