c#返回一个列表或int
本文关键字:一个 列表 int 返回 | 更新日期: 2023-09-27 18:11:53
是否可以在方法中返回List或int ?
类似:
- 如果成功:返回List
- 如果失败:返回int(给出错误编号)或带有错误消息的字符串。
(失败,因为没有异常,但值不正确,如PointF。X = <0或最低值大于10)。
现在我这样做:
public List<PointF> GetContourInfoFromFile(string a_file)
{
ListContourPoints.Clear();
List<string> textLines = new List<string>();
bool inEntitiesPart = false;
bool inContourPart = false;
try
{
foreach (string str in File.ReadAllLines(a_file))
{
textLines.Add(str);//Set complete file in array
}
for (int i = 0; i < textLines.Count; i++)
{
//read complete file and get information and set them in ListContourPoints
}
//Check Coordinate values
for (int i = 0; i < ListContourPoints.Count; i++)
{
//Coordinates are below -1!
if (ListContourPoints[i].X < -1 || ListContourPoints[i].Y < -1)
{
ListContourPoints.Clear();
break;
}
//Lowest X coordinate is not below 10!
if (mostLowestXContour(ListContourPoints) > 10)
{
ListContourPoints.Clear();
break;
}
//Lowest Y coordinate is not below 10!
if (mostLowestYContour(ListContourPoints) > 10)
{
ListContourPoints.Clear();
break;
}
}
}
catch (Exception E)
{
string Error = E.Message;
ListContourPoints.Clear();
}
return ListContourPoints;
}
当我这样做时,我知道值有问题。但不具体是什么
那么我怎么解决这个问题呢?如果不可能返回列表或字符串/int,最好的解决方案是什么?
你可以
解决方案1:
如果出错就抛出异常,并在上面的代码中执行try catch
删除你的函数中的catch部分,当你调用你的函数时,在try catch中这样做:
try
{
List<PointF> result = GetContourInfoFromFile(youfile);
}
catch (Exception E)
{
string Error = E.Message;
}
解决方案2:
返回一个带有Listresult和error属性的对象
您可以从catch块抛出异常,而不是返回一个数字,以便它可以被外部异常处理程序捕获。
下面是一个示例:
public void MainMethod()
{
try
{
var myList = SomeMethod();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // prints out "SomeMethod failed."
}
}
public List<object> SomeMethod()
{
try
{
int i = 1 + 1;
// Some process that may throw an exception
List<object> list = new List<object>();
list.Add(1);
list.Add(i);
return list;
}
catch (Exception ex)
{
Exception newEx = new Exception("SomeMethod failed.");
throw newEx;
}
}
您可以创建一个保存值或错误码的包装器类。例子:
public class Holder<T>
{
private Holder(T value)
{
WasSuccessful = true;
Value = value;
}
private Holder(int errorCode)
{
WasSuccessful = false;
ErrorCode = errorCode;
}
public bool WasSuccessful { get; }
public T Value { get; }
public int ErrorCode { get; }
public static Holder<T> Success(T value)
{
return new Holder<T>(value);
}
public static Holder<T> Fail(int errorCode)
{
return new Holder<T>(errorCode);
}
}
用法:
public Holder<PointF> MyFunc()
{
try
{
//
return Holder<PointF>.Success(new PointF());
}
catch
{
return Holder<PointF>.Fail(101);
}
}
一个解决方案是返回object
public object GetContourInfoFromFile(string a_file)
{
}
,在你调用this的方法中,试着同时转换为int和list,看看哪一个成功。
一个更精细的解决方案是有一个类
public class YourClassName{
public List<PointF> YourList {get; set;} //for success
public int YourVariable {get; set} // for failure
public string YourMEssage {get; set} // for failure
}
并返回
public YourClassName GetContourInfoFromFile(string a_file)
{
}