从属性获取器抛出 NotSupportedException

发布于 2024-12-29 19:11:00 字数 395 浏览 1 评论 0原文

我听说从财产获取者那里抛出异常是不合适的,并且我理解这个基本原理背后的原因。然而,以下情况让我感到困惑:想象一下,您正在编写一个旨在适应多个不同平台的外观:

public interface IFacade
{
    int SomeProperty { get; set; }
}

现在想象一下平台 XY 支持 SomeProperty< /code> 本身,但该平台 Z 没有。难道从平台 Z 适配器中的 getter 抛出 NotSupportedException 不应该是告诉用户该平台的特定情况不支持该功能的正确方法吗?

I have heard it is inappropriate to throw exceptions from property getters, and I understand the reasons behind this rationale. However, the following situation is puzzling me: Imagine you are writing a facade meant to adapt to several different platforms:

public interface IFacade
{
    int SomeProperty { get; set; }
}

Now imagine that platform X and Y support SomeProperty natively, but that platform Z does not. Shouldn't throwing NotSupportedException from the getter in platform Z's adapter be the right way to tell users that the functionality is not supported in that platform's particular case?

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

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

发布评论

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

评论(2

念三年u 2025-01-05 19:11:00

只要这种行为被记录下来,就没有任何问题。如果您担心处理异常的必要性,可以引入 SupportsSomeProperty 属性。然而,这可能会破坏界面。

As long as this behavior is documented there is nothing wrong about it. If you are concerned with necessity to handle the exception, you can introduce SupportsSomeProperty property. However, this can blow up the interface.

吃兔兔 2025-01-05 19:11:00

由于您知道无法捕获异常(对此您无能为力,该平台不受支持!),或者如果捕获了异常则无法处理,所以最好退出程序并显示一条错误消息,指出当前平台不支持。

异常通常用在可以捕获和处理的地方,或者在发生错误时意外抛出的地方。如果您发现程序在平台 z 上运行的错误,如果程序无法继续,则退出该程序。

Since you know that exception can't be caught (there's nothing you can do about it, the platform isn't suppported!), or handled if it is caught, it would be better to exit the program and display an error message saying that the current platform is not supported.

Exceptions are generally used in places where they can be caught and handled, or are thrown unexpectedly in event of error. If you catch an error that the program is running on platform z, then exit the program, if it cannot continue.

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