C#返回列表或整数

C#返回列表或整数,c#,error-handling,return,C#,Error Handling,Return,是否可以在方法中返回列表或int 比如: 如果成功:返回列表 如果失败:返回int(给出错误号)或带有错误消息的字符串 (失败,无异常,但值不正确,如PointF.X=低于0或最低值超过10) 现在我这样做: public List<PointF> GetContourInfoFromFile(string a_file) { ListContourPoints.Clear(); List<string> textLines = new List<

是否可以在方法中返回列表或int

比如:

  • 如果成功:返回列表
  • 如果失败:返回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;
}
try
{
    List<PointF> result = GetContourInfoFromFile(youfile);
}
catch (Exception E)
{
    string Error = E.Message;
}
public List GetContourInfoFromFile(字符串文件)
{
listpoints.Clear();
列表文本行=新列表();
bool-entitiespart=false;
布尔部分=假;
尝试
{
foreach(文件中的字符串str.ReadAllLines(a_文件))
{
textLines.Add(str);//在数组中设置完整的文件
}
对于(int i=0;i10)
{
listpoints.Clear();
打破
}
//最低Y坐标不低于10!
如果(mostLowestYContour(ListContourPoints)>10)
{
listpoints.Clear();
打破
}
}
}
捕获(例外E)
{
字符串错误=E.消息;
listpoints.Clear();
}
返回点;
}
当我这样做的时候,我知道te值有问题。。但不具体是什么


那么我该如何解决这个问题呢?如果无法返回列表或字符串/int,那么最好的解决方案是什么?

一种解决方案是返回对象

public object GetContourInfoFromFile(string a_file)
{

}
在调用此函数的方法中,尝试将其转换为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
}
你可以

解决方案1:

若出现错误,则抛出异常,并在上面的代码中执行try-catch

删除函数中的part catch,当调用函数时,在try catch中执行如下操作:

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;
}
try
{
    List<PointF> result = GetContourInfoFromFile(youfile);
}
catch (Exception E)
{
    string Error = E.Message;
}
试试看
{
列表结果=GetContourInfoFromFile(youfile);
}
捕获(例外E)
{
字符串错误=E.消息;
}
解决方案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 void main方法()
{
尝试
{
var myList=SomeMethod();
}
捕获(例外情况除外)
{
Console.WriteLine(ex.Message);//打印出“SomeMethod失败”
}
}
公共列表方法()
{
尝试
{
int i=1+1;
//可能引发异常的某些进程
列表=新列表();
增加第(1)款;
列表.添加(i);
退货清单;
}
捕获(例外情况除外)
{
Exception newEx=新异常(“SomeMethod失败”);
扔掉纽克斯;
}
}

您可以创建一个包含值或错误代码的包装类。例如:

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);
    }
}
公共类持有者
{
私人持有人(T值)
{
wasuccessful=true;
价值=价值;
}
私人持有人(国际错误代码)
{
成功=错误;
ErrorCode=错误代码;
}
公共布尔成功{get;}
公共T值{get;}
公共内部错误代码{get;}
公共静态持有者成功(T值)
{
返还新持有人(价值);
}
公共静态保持器故障(内部错误代码)
{
返回新的保持架(错误代码);
}
}
用法:

public Holder<PointF> MyFunc()
{
    try
    {
        //
        return Holder<PointF>.Success(new PointF());
    }
    catch
    {
        return Holder<PointF>.Fail(101);
    }
}
公共持有人MyFunc() { 尝试 { // 返回Holder.Success(新的PointF()); } 抓住 { 返回持有人。失败(101); } }
您是否考虑过在验证失败时自己引发异常,甚至可能是自定义异常,您可以给出您提到的错误号?是的,如果值超出范围,您真的应该引发异常。此外,如果这些值是由用户输入的,那么在将输入传递到
GetContourInfoFromFile()
之前,您应该调用一个单独的验证方法来清理输入(并且该验证方法不必抛出异常;成功时它可以返回
null
,失败时返回错误消息字符串)如果文件中的值不正确,则应终止正常行为。例外是一个很好的解决方案。但您需要确保在更高级别捕获异常,以通知用户该文件不正确。@MatthewWatson此方法实际上是检查值并查看它们是否正确。失败时,您所说的返回
null
,正是我现在所做的。重点是我想告诉用户他做错了什么,比如X低于零。或者Y大于10。@我的意思是,如果项目是由用户通过UI输入的——如果是从文件中读取的,则不是由用户直接输入的——因此抛出异常是可以的。但是,您的方法要做两件事:(1)从文件中加载和解析一组数据,以及(2)在加载数据后验证数据中的值。这违反了SRP,您应该将其分为两个方法。我选择解决方案1,因为如果值不正确,则应“终止”正常处理。