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

发布于 2025-01-01 05:43:35 字数 709 浏览 1 评论 0原文

我只是尝试在 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.
        }

    }
}

I just tried to implement Singleton pattern to WinForms ,so that only one instance of a form stays in the Application life ,but i face a difficulty

I want to throw exception if the instance of singleton exists and return same instance reference at the same time.

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.
        }

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清晰传感 2025-01-08 05:43:35

您要么抛出异常,要么返回一个实例。对于单例,不应抛出异常,只需返回实例(如果存在)。

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

我只是想也许有时我可能需要同时使用两者
这就是我问的原因

“抛出异常立即从函数返回”,因为这意味着发生了意外错误。在另一种情况下,您可能想抛出异常,但前提是某些条件为真(例如参数验证失败)。否则,您将返回一个值。这是一个例子:

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

You either throw an Exception, or return an instance. In the case of a Singleton, no Exception should be thrown, just return the instance if it exists.

The Singleton pattern shouldn't stop you (or even warn you) from calling GetInstance many times. It should just return the same instance that was created the first time around.

i just thought may be sometime i may need to use both at the same time
thats why I asked

Throwing an exception returns immediately from the function, because it means that an unexpected error occurs. In another situation, you might want to throw an exception, but only if some condition is true (e.g. argument validation failed). Otherwise, you return a value. Here's an example:

public int SomeFunction(String someArgument)
{
    if (someArgument == null) throw new ArgumentNullException("someArgument");
    int retVal = 0;
    //Some code here
    return retVal;
}
<逆流佳人身旁 2025-01-08 05:43:35

从设计的角度来看,不,你不需要。异常应该代表系统需要恢复的严重的、意外的错误。您正在谈论将其用作错误代码。如果您打算这样做,请不要抛出异常 - 通过在单例上设置标志或返回 null 或其他内容来指示问题。

但是,在您的具体情况下,只需删除异常逻辑即可。单例设计模式旨在成为全局变量的存储库,因此预计公共静态实例将被多次调用(事实上,单例的许多用户倾向于在其代码库中的几乎每个类中使用它)。

From a design standpoint, no, you don't. An exception should represent a serious, unanticipated error from which your system needs to recover. You're talking about using it as an error code. If you're going to do that, don't throw an exception -- indicate a problem by setting a flag on your singleton or returning a null or something.

However, in your specific case, just get rid of the exception logic. The singleton design pattern is intended to be a repository for global variables, so it is expected that the public static instance will be called more than once (in fact, many users of singleton tend to use it in just about every class in their code base).

百变从容 2025-01-08 05:43:35

我正在假设您有一种情况,您实际上需要知道它是否是一个新实例,并且它将在返回后更改您的执行路径。一种方法是(尽管我不敢输入这个)使用异常(选项 1)。但您更有可能希望使用选项 2 来简单地根据返回值进行分支。

public class SingletonForm : BaseFormcs
{
    private static SingletonForm _instance;
    //To stop new keyword from instantiation 
    private SingletonForm()
    { }
    // ------- Option #1
    // Use an OUT parameter for the instance, so it's set before the exception
    public static void GetInstance(out SingletonForm form)
    {
        if (_instance == null)
        {
            _instance = new SingletonForm();
            form = _instance;
            return;
        }
        form = _instance;
        throw new Exception("Form already exists"); // execution returns from here
        // return isn't needed, since you threw an exception.
        // You really, really shouldn't do this. Consider instead...
    }

    // -------- Option #2
    // Same as above, but the return value tells you whether it's shiny and new
    public static bool GetInstance(out SingletonForm form)
    {
        if (_instance == null)
        {
            _instance = new SingletonForm();
            form = _instance;
            return true; // yes, you created a new one
        }
        form = _instance;
        return false; // no, you used an extant one
    }
}

第二个选项可能是您最好的选择,因为它更符合您在 Dictionary.TryGetValue(KEY key, out VALUE value) 中看到的内容。

I'm working on the assumption that you have a case where you actually need to know whether it's a new instance, and that it's going to change your execution path following the return. One way is (though I shudder to type this) using exceptions (option 1). But it's more likely that you'd want to use option 2 to simply branch on the return value.

public class SingletonForm : BaseFormcs
{
    private static SingletonForm _instance;
    //To stop new keyword from instantiation 
    private SingletonForm()
    { }
    // ------- Option #1
    // Use an OUT parameter for the instance, so it's set before the exception
    public static void GetInstance(out SingletonForm form)
    {
        if (_instance == null)
        {
            _instance = new SingletonForm();
            form = _instance;
            return;
        }
        form = _instance;
        throw new Exception("Form already exists"); // execution returns from here
        // return isn't needed, since you threw an exception.
        // You really, really shouldn't do this. Consider instead...
    }

    // -------- Option #2
    // Same as above, but the return value tells you whether it's shiny and new
    public static bool GetInstance(out SingletonForm form)
    {
        if (_instance == null)
        {
            _instance = new SingletonForm();
            form = _instance;
            return true; // yes, you created a new one
        }
        form = _instance;
        return false; // no, you used an extant one
    }
}

This second option is probably your best bet, since it's more along the lines of what you'd see in Dictionary.TryGetValue(KEY key, out VALUE value).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文