C#抛出然后继续返回

KVN*_*KVN 0 c#

我在我的方法中使用了 try/catch。当然,如果发生异常,它会抛出异常(我的 UnitTest 部分需要这个异常),但不会返回值。

我想要的是 catch 部分同时执行:抛出异常并返回值。

有没有办法做到这一点?

这是我的示例代码(并且返回计数不应为“0”):

    private int myCount;

    public void DoSomethingMethod()
{
     // Do Something Here
     myCount++;
}

    public int MyMethod ()
            {
                try
                {
                    DoSomethingMethod()
                    return myCount;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                    return myCount; // Do not expect this value to be '0'
                }
            }
Run Code Online (Sandbox Code Playgroud)

这是需要这两者的测试部分(异常和返回计数)。

[Test]
        public void when_expected_count()
        {
            int count= 0;
            Action act = () => count= MyMethod.GetResult();

            act.Should().Throw<Exception>("The method should throw Exception.");
            count.Should().Be(10);
        }
Run Code Online (Sandbox Code Playgroud)

Ruf*_*s L 6

throw并且return两者都退出该方法,因此您必须选择一个。

一种选择是返回一个同时具有Count属性和Exception属性的对象,这样客户端就可以获取计数值并检查是否有错误:

private int myCount;

public class CountWithException
{
    public int Count { get; set; }
    public Exception Exception { get; set; }
}

public CountWithException MyMethod()
{
    try
    {
        // Do something here
        myCount++;

        // Return an object with the count property set
        return new CountWithException {Count = myCount};
    }
    catch (Exception ex)
    {
        myCount--;

        // Return an object with both the count AND exception properties set
        return new CountWithException { Count = myCount, Exception = ex};
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,catch客户端的a不会被触发。然后客户端必须执行以下操作:

var result = SomeClass.MyMethod();

var count = result.Count;  // Example of getting the 'count' return value

if (result.Exception != null)
{
    // Do something if the method "threw an excpetion"
}
Run Code Online (Sandbox Code Playgroud)