我是OOP和C#的新手,我希望这里缺少一些基本知识。.我可能可以在这里使用Tuples语法,但是我试图将其与基本OOP概念一起使用。.我有一个Validator类,如果输入不正确,我想知道为什么会失败。这是我的尝试..如何从Main()获取'Msg'字符串值?警告...前面的错误代码...
class Validator
{
public int Age { get; set; }
public string Location { get; set; }
public string Msg { get; set; }
public bool IsAgeValid()
{
if (Age < 18)
{
Msg = "Not old enough";
return false;
}
else if (Age > 25)
{
Msg = "you are very old";
return false;
}
else
{
return true;
}
}
public bool IsLocationValid()
{
if (Location == "EARTH")
{
return true;
}
else
{
Msg = "sorry..only for humans";
return false;
}
}
public bool IsValid()
{
if (IsAgeValid() && IsLocationValid())
{
return true;
}
return false;
}
public string getErrorMessage()
{
return Msg;
}
}
static void Main()
{
Validator myValidator = new Validator();
myValidator.Age = 34;
myValidator.Location = "EARTH";
if(myValidator.IsValid())
{
Console.WriteLine("good");
}
else
{
if(myValidator.IsValid)
Console.WriteLine("bad because " + myValidator.getErrorMessage());
}
}
看起来第二条if语句妨碍了操作,如果IsValid返回布尔值,则这是多余的。尝试以下代码,看看它是否按预期工作: