同时从方法返回对象引用和异常

Owa*_*shi 1 c# singleton

我只是尝试将单例模式实现为WinForms,因此只有一个表单实例保留在应用程序生命中,但是我遇到了困难

如果单例实例存在并且同时返回相同的实例引用,我想抛出异常.

SingletonForm.cs

public class SingletonForm : BaseFormcs
{
    private static SingletonForm _instance;
    //To stop new keyword from instantiation 
    private SingletonForm()
    { }
    public static SingletonForm GetInstance()
    {
        if (_instance == null)
            return _instance = new SingletonForm();

        else
        {
            throw new Exception("Form already exists"); // execution returns from here
            return _instance; // Warning : Unreachable code detected
            //I also want to return instance reference.
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Met*_*ght 6

您要么抛出异常,要么返回实例.对于Singleton,不应抛出异常,只返回实例(如果存在).

Singleton模式不应该阻止你(甚至警告你)多次调用GetInstance.它应该只返回第一次创建的同一个实例.

我只是觉得可能有时我可能需要同时使用这两个,这就是我问的原因

抛出异常会立即从函数返回,因为这意味着发生意外错误.在另一种情况下,您可能希望抛出异常,但仅在某些条件为真时(例如,参数验证失败).否则,返回一个值.这是一个例子:

public int SomeFunction(String someArgument)
{
    if (someArgument == null) throw new ArgumentNullException("someArgument");
    int retVal = 0;
    //Some code here
    return retVal;
}
Run Code Online (Sandbox Code Playgroud)