Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.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# 创建一个方法,如果在c中该类的任何方法中发生异常,该方法将捕获异常#_C#_.net_Try Catch_Method Chaining - Fatal编程技术网

C# 创建一个方法,如果在c中该类的任何方法中发生异常,该方法将捕获异常#

C# 创建一个方法,如果在c中该类的任何方法中发生异常,该方法将捕获异常#,c#,.net,try-catch,method-chaining,C#,.net,Try Catch,Method Chaining,我有一个类Demo,它有四个方法,分别是Add(),Update(),Delete()和Get() 这些方法链接在一起,如下所示: bool isSuccess = this.Get(1) .Update(200) //new product price bool isSuccess = this.Get(1) .Update(200); //new product price

我有一个类
Demo
,它有四个方法,分别是
Add()
Update()
Delete()
Get()

这些方法链接在一起,如下所示:

bool isSuccess = this.Get(1)
                    .Update(200) //new product price
bool isSuccess = this.Get(1)
                    .Update(200); //new product price
                    .CatchError();
现在,我想实现
CatchError()
方法,如果上述任何一种方法中发生了
异常,它将捕获
异常

代码如下所示:

bool isSuccess = this.Get(1)
                    .Update(200) //new product price
bool isSuccess = this.Get(1)
                    .Update(200); //new product price
                    .CatchError();
我不知道如何实现
CatchError()
方法


我们很乐意提供额外的信息来帮助您正确回答问题。

要实现这一点,您应该只在调用CatchError时执行所有操作。在此之前,您应该收集所有必须执行的操作。 比如:

public class Demo
{
    private int Value;
    private List<Action> Operations = new List<Action>();
    public Demo Get(int a)
    {
        this.Operations.Add(() => this.Value = a);
        return this;
    }

    public Demo Update(int a)
    {
        this.Operations.Add(() => this.Value += a);
        return this;
    }

    public bool CatchError()
    {
        foreach (var operation in Operations)
        {
            try
            {
                operation();
            }
            catch (Exception e)
            {
                return false;
            }
        }
        Operations.Clear();
        return true;
    }
}
公共类演示
{
私有int值;
私有列表操作=新列表();
公共演示获取(INTA)
{
this.Operations.Add(()=>this.Value=a);
归还这个;
}
公共演示更新(INTA)
{
this.Operations.Add(()=>this.Value+=a);
归还这个;
}
公共boolcatcherror()
{
foreach(操作中的var操作)
{
尝试
{
操作();
}
捕获(例外e)
{
返回false;
}
}
操作。清除();
返回true;
}
}

就像我在评论中写的那样,我将尝试创建一个方法CatchError(),其中您将动作作为参数:

bool isSuccess = CatchError(() => Get(1).Update(200));
您的CatchError()方法如下所示:

private static bool CatchError(Action action)
{
    try
    {
        action();
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

如果您在fluent API中创建一个方法来捕获异常,那么您还需要决定是否要继续执行fluent调用。代码如下

如果不需要创建一个流畅的方法,我会建议,因为它不那么复杂

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        bool processCancelled = false;
        myCar.SubscribeOnError(CarOnError).Paint(ref processCancelled, "red").Sell(ref processCancelled, 25000d);
    }

    public static bool CarOnError(Exception e)
    {
        // Log exception
        // Decide if must cancel
        return true;
    }
}

public class Car
{
    private Func<Exception, bool> onErrorMethod = null;

    public Car SubscribeOnError(Func<Exception, bool> methodToCall)
    {
        onErrorMethod = methodToCall;
        return this;
    }
    public Car Paint(ref bool cancelled, string color)
    {
        if (cancelled) return this;
        try
        {
            // Do stuff
        }
        catch (Exception exc)
        {
            cancelled = onErrorMethod == null ? true : onErrorMethod(exc);
        }
        return this;
    }
    public Car Sell(ref bool cancelled, double price)
    {
        if (cancelled) return this;
        try
        {
            // Do stuff
        }
        catch (Exception exc)
        {
            cancelled = onErrorMethod == null ? true : onErrorMethod(exc);
        }
        return this;
    }
}
类程序
{
静态void Main(字符串[]参数)
{
我的车=新车();
bool processCancelled=false;
myCar.SubscribeOnError(CarOneError)。油漆(参考流程取消,“红色”)。销售(参考流程取消,25000d);
}
公共静态bool CarOnError(例外e)
{
//日志异常
//决定是否必须取消
返回true;
}
}
公车
{
private Func onErrorMethod=null;
公共汽车订户错误(Func methodToCall)
{
onErrorMethod=methodToCall;
归还这个;
}
公共汽车油漆(参考编号已取消,字符串颜色)
{
如果(取消)返回此文件;
尝试
{
//做事
}
捕获(异常exc)
{
cancelled=OneErrorMethod==null?true:OneErrorMethod(exc);
}
归还这个;
}
公共汽车销售(参考价格取消,双倍价格)
{
如果(取消)返回此文件;
尝试
{
//做事
}
捕获(异常exc)
{
cancelled=OneErrorMethod==null?true:OneErrorMethod(exc);
}
归还这个;
}
}

创建一个带有action/Func参数的
CatchError()
方法是否是一个解决方案。参数是this.Get(1.Update(200)
。该参数将类似于@JeroenMostert在下一条注释中所写的参数。-->
()=>this.Get(1).Update(200)
您不能将其作为方法上的链来实现。但是,您可以实现一个方法来包装
操作
,这样您就可以将
()=>this.Get(1).Update(200)
传递给它。(虽然从技术上讲,你可以将这样一个
动作
与一个扩展方法链接起来,但这些方法往往比它们阐明的更模糊。)所有的方法(
Get
Update
,等等)都返回了什么?为什么你不
this.SubscribeOnError(Class\OnError).Get(1).Update(200)
这样,如果方法出现错误,您只需要在方法中提出
CancelEventHandler
。添加了一个没有事件的答案,但只调用函数@BijayYadavYeah,但是如果询问者(或其他人)编写了类似
someDemo.Update(…)的代码怎么办没有附加
CatchError()
?这种方法很容易导致编写错误的代码,而这些代码在查看代码时并没有达到预期的效果……在调用方法时,一个流畅的API应该如何执行操作。@elgonzo这取决于整个构造的使用方式。如果将使用builder模式,我们将在最后调用一些“Build”方法,它可能是BuildAndCatchError。重要的是要知道这些操作到底在做什么,以及应该如何访问结果。@MaksimSimkin,我同意问题中给出的方法名称的含义。你的回答可能很适合不同的场景,但它不适合我们从问题中了解到的情况……从另一个侧面来看,也不太适合问题所涉及的实际问题(因此,实际上只是一个侧面):除非处理令人烦恼的例外情况,捕获异常并完全忽略异常信息及其指示的异常情况/问题通常不是一个好主意,因为这样会丢失/忽略在解决程序/软件问题时非常有用或非常重要的信息…没错。因此,如果有人使用此代码,则应在catch中进行异常处理。这意味着他应该记录它,或者向用户显示它。但我只想展示一个用方法捕获异常的机会。