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
轮询时都不会被调用.