Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#当类型为string时,执行catch块_C#_Asp.net Mvc - Fatal编程技术网

C#当类型为string时,执行catch块

C#当类型为string时,执行catch块,c#,asp.net-mvc,C#,Asp.net Mvc,在这里,我很难处理catch块,就像我想在值类型为字符串时执行catch块一样 在这里,当方法返回时,我使用动态类型接受所有类型的值 现在我想在方法返回字符串类型时执行catch块。 这是我的密码 dynamic paymentResult = null; try { paymentResult = await ExecuteSquarePayment(db, checkoutViewModel); } catch (Exception ex) when (paymentResult i

在这里,我很难处理catch块,就像我想在值类型为字符串时执行catch块一样

在这里,当方法返回时,我使用动态类型接受所有类型的值

现在我想在方法返回字符串类型时执行catch块。 这是我的密码

dynamic paymentResult = null;
try
{
    paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
    return Content(HttpStatusCode.InternalServerError,
        $"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}

你不需要一个挡块<代码>重试捕获用于处理异常。如果是预期行为,只需测试
类型

 dynamic paymentResult = null;

 paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);

 if(paymentResult is string)
 {
      return Content(HttpStatusCode.InternalServerError, $"
           {Messages.DonationPaymentFailed} 
           {checkoutViewModel.PaymentMethod} : paymentResult is a string");
 }
如果出于某种原因确实需要在catch块中执行此操作,则必须抛出一个
异常

dynamic paymentResult = null;

try
{
     paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);

     if(paymentResult is string)
     {
         throw new Exception("The result was of type string");
     }
 }
 catch (Exception ex) 
 {
    return Content(HttpStatusCode.InternalServerError, $"
           {Messages.DonationPaymentFailed} 
           {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
 }

我猜您在
ExecuteSquarePayment
中签入了正确类型的参数,对吗?如果是这样,为什么不简单地使用
catch块
,而不使用类型限制呢。如果参数类型正确,则不会出现错误


对于参数可能是的其他类型,我看不到任何不同的
返回值。

我猜,如果ExecuteSquarePayment方法引发异常,paymentResult将始终为null(未设置)。

try catch
块用于,您应该只使用
if(paymentResult为string)
。在c#6中,我们可以定义异常,我们可以使用when根据条件执行多个catch块。reference当
paymentResult
仍为
null
时,您希望在任何情况下引发什么异常?我想他需要
ex.ToString()
来显示来自
ExecuteSquarePayment
调用的一些业务异常消息,如果ExecuteSquarePayment抛出,则不会设置paymentResult,因此when条件无论如何都不会成功。您是对的,但是当返回类型为字符串时,如何测试动态类型为字符串。正如我所示
if(paymentResult为string)
如果
ExecuteSquarePayment
的结果为string,则将为true。ExecuteSquarePayment方法将返回动态类型这意味着该方法可能返回string、int或其他任何值