c# OOP打印结果
本文关键字:结果 打印 OOP | 更新日期: 2023-09-27 18:14:31
我是visual studio c#的新手,我试图使用OOP打印结果我想将结果打印为:
你好。我是一只可卡犬。汪!我是(大或小),颜色是白色的,我有四条腿。
由于我设置的值是10,所以它总是很小…
下面是我的代码:public Dog()
{
barkSound = "Woof!";
breed = "cocker spaniel";
dogHeight = 10;
dogColour = "white";
noOfLEgs = 4;
}
public string GetSpeech()
{
dogSpeech = "Hello. I am a " + breed + ". " + barkSound + " I'm "
+ dogHeight + ", Colour is " + dogColour + ", I have " + noOfLEgs +" legs" ;
return dogSpeech;
}
private bool IsBig(int dogHeight)
{
if (dogHeight < 50)
{
return false;
} else
{
return true;
}
}
我应该修改"IsBig"方法或另一种更好的方式来打印预期的结果?
有两种方法。
您可以将IsBig
重命名为GetSizeDescription
并返回字符串:
private string GetSizeDescription() {
if (dogHeight < 50)
{
return "Small";
} else
{
return "Big";
}
}
用法:
public string GetSpeech()
{
dogSpeech = "Hello. I am a " + breed + ". " + barkSound + " I'm "
+ GetSizeDescription() + ", Colour is " + dogColour + ", I have " + noOfLEgs +" legs" ;
return dogSpeech;
}
或者,可以保持IsBig
方法不变,将GetSpeech
方法改为:
public string GetSpeech()
{
dogSpeech = "Hello. I am a " + breed + ". " + barkSound + " I'm "
+ (IsBig() ? "Big" : "Small") + ", Colour is " + dogColour + ", I have " + noOfLEgs +" legs" ;
return dogSpeech;
}
可以修改方法
private string GetSizeString(int dogHeight)
{
if (dogHeight < 50)
{
return "Small";
}
return "Big";
}
然后直接
public string GetSpeech()
{
return "Hello. I am a " + breed + ". " + barkSound + " I'm "
+ GetSizeString(dogHeight) + ", Colour is " + dogColour + ", I have " + noOfLEgs +" legs" ;
}
这是您的完整代码。
public class Dog
{
public Dog()
{
barkSound = "Woof!";
breed = "cocker spaniel";
dogHeight = 10;
dogColour = "white";
noOfLEgs = 4;
}
public string barkSound { get; private set; }
public string breed { get; private set; }
public string dogColour { get; private set; }
public int dogHeight { get; private set; }
public int noOfLEgs { get; private set; }
public string GetSpeech()
{
string dogSpeech = "Hello. I am a " + breed + ". " + barkSound + " I'm "
+ (IsBig(dogHeight) ? "Big" : "Small") + ", Colour is " + dogColour + ", I have " + noOfLEgs + " legs";
return dogSpeech;
}
private bool IsBig(int dogHeight)
{
if (dogHeight < 50)
{
return false;
}
else
{
return true;
}
}
}
呼叫应该是这样的。
Dog dog = new Dog();
string speech = dog.GetSpeech();
将dogHeight
替换为(IsBig(dogHeight) ? "Big" : "Small")
,就这样。
你不应该修改IsBig方法。也许你应该让它成为一个属性,但这不是很重要。你可以创建一个新方法:
private string GetSizeText(bool isBig)
{
if (isBig)
return "Big";
return "Small";
}
那么你的GetSpeech看起来像:
public string GetSpeech()
{
dogSpeech = "Hello. I am a " + breed + ". " + barkSound + " I'm "
+ GetSizeText(IsBig(dogHeight)) + ", Colour is " + dogColour + ", I have " + noOfLEgs +" legs" ;
return dogSpeech;
}
这是一个简单的解决方案。您还可以创建一个以Big和Small作为值的枚举,并使用ToString();
打印此枚举值。