根据条件返回消息的方法

时间:2014-04-23 16:07:23

标签: vb.net string console-application

我遇到一种情况,如果try,catch块中存在异常,方法应该返回两条消息,如果没有异常,它应该返回一条成功消息。

我在另一个类中调用此方法并将其结果分配给string。我可以连接异常方法并将其作为单个消息发送到此类。但是,我必须再次分割这个消息。

有没有办法拆分字符串消息?

示例代码:

public class sendMessage
    sub main()
        method()
    end sub

    public function method() as string
        try
            ------------
            if response isnot nothing
                message= "success"
            end if
       catch
           message="failure"+" "
           message+=ex.tostring()
       end try
       return message
    end function 
end class


public class invokeMessage
    sub main()
        dim ob as new sendMessage
        dim message = ob.method()
        dim messageStatus=? ------------this can be success or failure
        dim messageException ----------- this has exception message in case of failure
    end sub
end class

2 个答案:

答案 0 :(得分:2)

如果需要从函数返回多个值,则:

1 - 定义返回类型

public class MyReturnResult
{
    public bool IsException;
    public string Message;
}

public MyReturnResult MyMethod()
{
    try
    {
       ...
    }
    catch (Exception e)
    {
        return new MyReturnResult() {IsException = true, Message = e.ToString()};
    }
    // can be inside try
    return new MyReturnResult() {IsException = false, Message = "Ok"};
}

2 - 使用着名的GetLastError主题

public string LastMessage;

public bool MyMethod()
{
    try
    {
       ...
    }
    catch (Exception e)
    {
        LastMessage = e.ToString();
        return true;
    }
    LastMessage = "Ok";
    return false; // no exception
}

3 - 使用out参数

// or make bool function and string out parameter
public string MyMethod(out bool isException)
{
    try
    {
       ...
    }
    catch (Exception e)
    {
        isException = true;
        return e.ToString();
    }
    isException = false;
    return "Ok";
}

在您的情况下,您可以定义特殊字符串(例如,"blablablaOk"null值)以指示无异常的情况,否则它会指示存在异常的内容,并且包含与该异常消息不同的

public string MyMethod()
{
    try
    {
       ...
    }
    catch (Exception e)
    {
        return e.ToString();
    }
    return "blablablaOk";
}

然后检查

if(MyMethod() == "blablablaOk")
{
    // no exception
}
else
{
}

答案 1 :(得分:1)

public class sendMessage
    sub main()
        method()
    end sub

    public function method() as string
        try
            ------------
            if response isnot nothing
            message= "success"
            end if
       catch
           message="failure"+" "
           message+=ex.tostring()
       end try
       return message
    end function 
end class


public class invokeMessage
    sub main()
        dim ob as new sendMessage
        dim message = ob.method()
        if message.contains(separator)
            dim messages() as string = message.split(separator) // array of 2 elements with "failure" + "rest of the message"
   end sub
end class