如何在派生类中使用C#赶上从构造函数的异常?函数、类中、异常、如何在

2023-09-04 13:19:07 作者:難尋難迴味

我想知道如何在派生类中使用C#赶上从构造函数的异常。有些事情是如此这样的:

 公共类MyClassA
{
    公共MyClassA()
    {
        //做的工作
        如果(失败)
        {
            抛出新的异常(我的异常);
        }
    }
}

公共类MyClassB:MyClassA
{
    公共MyClassB()
    {
        //如何从MyClassA构造赶上例外?
    }
}
 

解决方案

甚至不要试图找出如何做到这一点。如果基类的构造函数抛出异常,这意味着基类是在一个糟糕的状态。如果基类是在一个糟糕的状态,这意味着派生类是在一个糟糕的状态。构造函数的关键是让一个对象进入可用状态。它失败了。滚出去!

I was wondering how to catch an exception from a constructor in a derived class with C#. Something as such:

public class MyClassA
{
    public MyClassA()
    {
        //Do the work
        if (failed)
        {
            throw new Exception("My exception");
        }
    }
}

public class MyClassB : MyClassA
{
    public MyClassB()
    {
        //How to catch exception from a constructor in MyClassA?
    }
}
C 派生类函数定义,我被彻底弄晕了

解决方案

Do not even try to figure out how to do this. If the base class constructor is throwing an exception, it means the base class is in a bad state. If the base class is in a bad state, it means the derived class is in a bad state. The point of a constructor is to get an object into a useable state. It failed. Get out!

 
精彩推荐
图片推荐