简体   繁体   English

C# 返回一个列表或一个 int

[英]C# returning a list OR an int

Is it possible to return a List OR an int in a method?是否可以在方法中返回 List 或 int?

Something like:类似的东西:

  • if it succeeded: return List如果成功:返回列表
  • if it failed: return int (that gives an error number) or string with error message.如果失败:返回 int(给出错误编号)或带有错误消息的字符串。

(failed as in no exceptions but the values are incorrect, like PointF.X = below 0 or Lowest value is over 10). (无一例外地失败,但值不正确,例如 PointF.X = 低于 0 或最低值超过 10)。

Now I'm doing it like this:现在我这样做:

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;
}

When I do it like this, I know there is something wrong with te values.. but not specifically what.当我这样做时,我知道 te 值有问题..但不具体是什么。

So how can I solve this?那么我该如何解决这个问题呢? If it's not possible with returning a list OR string/int, what's the best solution?如果无法返回列表或字符串/整数,最好的解决方案是什么?

You can你可以

Solution 1:解决方案1:

throw exception if error, and in your code above do a try catch如果出错则抛出异常,并在上面的代码中执行 try catch

Delete the part catch in your function, and when you call you function do it in try catch like this:删除函数中的部分 catch,当你调用函数时,像这样在 try catch 中执行它:

try
{
    List<PointF> result = GetContourInfoFromFile(youfile);
}
catch (Exception E)
{
    string Error = E.Message;
}

Solution 2:解决方案2:

return an object with Listresult and error as property返回一个带有 Listresult 和 error 作为属性的对象

Instead of returning a number, you can throw an exception from the catch block so that it can be caught by the outer exception handler.您可以从 catch 块中抛出一个异常,而不是返回一个数字,以便它可以被外部异常处理程序捕获。

Here's a sample:这是一个示例:

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;
    }
}

you could create a wrapper class which holds either the value or the errorcode.您可以创建一个包含值或错误代码的包装类。 Example:示例:

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);
    }
}

Usage:用法:

public Holder<PointF> MyFunc()
{
    try
    {
        //
        return Holder<PointF>.Success(new PointF());
    }
    catch
    {
        return Holder<PointF>.Fail(101);
    }
}

one solution would be to return object一种解决方案是返回对象

public object GetContourInfoFromFile(string a_file)
{

}

and in the method where you call this try to cast to both int and list and see which one succeeds.并在您调用此方法的方法中尝试同时转换为 int 和 list 并查看哪个成功。

a more elaborate solution would be to have a class一个更复杂的解决方案是有一个类

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
}

and return that one并返回那个

public YourClassName GetContourInfoFromFile(string a_file)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM