gpt4 book ai didi

c# - NotImplementedException——但它是永远不应该被调用的东西

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:17 25 4
gpt4 key购买 nike

从逻辑上讲,所讨论的方法应该是抽象的,但它们位于继承自的父窗体上,如果将它们声明为抽象的,Visual Studio 将适用。

好的,我让尸体抛出一个NotImplementedException。 Resharper 标记了这一点,我不能容忍在代码中出现这样的警告。

对此有一个优雅的答案还是我必须忍受一些丑陋?目前我在做:

protected virtual void SaveCurrentItem()
{
Trace.Assert(false, "Only the children of FormCore.SaveCurrentItem should be called");
}

protected virtual void SetItem()
{
Trace.Assert(false, "Only the children of FormCore.SetItem should be called");
}

类本身不应该被实例化,只有它的 child 。但是,当您查看其中一个子项的设计器时,Visual Studio 坚持要创建一个。

最佳答案

您可以考虑创建一个嵌套的、 protected 接口(interface)。例如:

protected interface IManageItems
{
void SaveCurrentItem();
void SetItem();
}

每个继承自 FormCore 的类都可以单独实现该接口(interface)。这样您就不会有调用基类实现的风险,因为根本没有。

从基类调用方法:

(this as IManageItems)?.SaveCurrentItem();

这会产生这样的效果,即在父类中没有初始声明的情况下,这些方法就好像它们是 virtual 一样。如果您想强制执行更接近于 abstract 的行为,您可以检查接口(interface)是否在基类的构造函数中实现,如果没有,则抛出异常。事情显然变得有点不稳定,因为这本质上是 IDE 阻止你做的事情的变通方法,因此没有真正干净的标准解决方案来解决这样的问题。我敢肯定,大多数人看到嵌套的 protected 接口(interface)都会畏缩,但如果您不想在基类中实现,并且不能将基类标记为抽象,那么您没有太多选择.

要考虑的另一件事是 favoring composition over inheritance提供您需要的功能。


另一方面,在类无法执行操作的情况下,不使用接口(interface),简单地抛出 NotSupportedException 可能是合适的。 NotImplementedException 旨在仅用于开发中的项目,这就是 ReSharper 标记该方法的原因。

NotSupportedException: The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.

一个用例是:

You've inherited from an abstract class that requires that you override a number of methods. However, you're only prepared to provide an implementation for a subset of these. For the methods that you decide not to implement, you can choose to throw a NotSupportedException.

参见 NotSupportedException documentation on MSDN获取更多信息和使用指南。

关于c# - NotImplementedException——但它是永远不应该被调用的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com