我目前正在使用C#类,在类中我们希望从我们的主代码中获取错误处理,并为另一个类中的所有整数构建所有错误处理和数据解析,但问题是你只能返回一个变量。
如何将“true / false”(bool)和解析后的数据从一个类返回到另一个类。
Class1.cs(主要代码)
int num1;
Class2 class2Object = new Class2();
public Class1()
{
//constructor
}
public void Num1Method()
{
string tempVal = "";
bool errorFlag; //bool = true/false
do
{
errorFlag = false; //no error & initialize
Console.Write("Enter Num1: ");
tempVal = Console.ReadLine();
class2Object.IntErrorCheckMethod(tempVal);
}//close do
while (errorFlag == true);
}//close Num1Method
Class2.cs(错误和解析处理)
public bool IntErrorCheckMethod(string xTempVal)
{
int tempNum = 0;
bool errorFlag = false;
try
{
tempNum = int.Parse(xTempVal);
}
catch(FormatException)
{
errorFlag = true;
tempNum = 999;
}
return errorFlag;
}//close int error check
所以Class2只返回true / false(如果有错误),我怎样才能将好的解析数据返回给Class1放入“int num1”变量?
我们的教授只能考虑删除bool并使用虚拟值(如果数据有错误,将值设置为999并返回它,然后执行if ifif来检查值是否为999然后返回错误消息,否则将数据提交给变量。
我认为能够使用bool作为错误的更好的代码,因为999可能是用户输入的好数据。
感谢任何想法, 谢谢!
答案 0 :(得分:1)
您可以像使用.NET中的out parameter方法一样使用TryParse。 BTW 而不是你的方法,你可以使用
int tempNum;
errorFlag = Int32.TryParse(string, out tempNum);
或者,如果您真的想使用自己的方法进行解析:
public bool IntErrorCheckMethod(string xTempVal, out int tempNum)
{
tempNum = 0;
bool errorFlag = false;
try
{
tempNum = int.Parse(xTempVal);
}
catch(FormatException)
{
errorFlag = true;
tempNum = 999;
}
return errorFlag;
}
用法:
int num1;
public void Num1Method()
{
string tempVal;
do
{
Console.Write("Enter Num1: ");
tempVal = Console.ReadLine();
}
while(class2Object.IntErrorCheckMethod(tempVal, out num1));
}
还要考虑对您的方法进行一些重构:
public bool TryParse(string s, out int result)
{
result = 0;
try
{
result = Int32.Parse(s);
return true; // parsing succeed
}
catch(FormatException)
{
return false; // parsing failed, you don't care of result value
}
}