如何不实现类的接口的功能? [英] How not to implement a function of an interface in class?

查看:192
本文介绍了如何不实现类的接口的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是面试官问我在采访中以下问题,但我不知道这可能是这个问题,请帮助!

An interviewer asked me the following question in interview, but I don't know what could be the answer of this question, please help!!!

如果我不想
落实在我班上一个函数,
是由我的类实现
接口中声明必须做什么。

What must be done if i don't want to implement a function in my class that is declared in an interface which is implemented by my class.

编辑:我使用与C#.NET。这将是巨大的,如果任何人都可以提供C#示例代码示例。

Edited: I am using .NET with C#. It will be great if anyone can provide a sample code example in C#.

感谢

推荐答案

在实施执行的功能,但抛出一个异常

Implement the function, but throw an exception in the implementation.

在.NET中,您通常使用的一下面(有其他语言类似的异常类型)。

In .NET, you typically use one of the following (there are similar exception types in other languages).

引发NotSupportedException :目前的不会的这个类中的方法的实现,由设计。这个多次出现在基类中,在派生类中,预计在适用情况下,提供一个实现虚拟方法。它也出现在显式接口实现方法(←这是具体的事情面试官问),如 ReadOnlyCollection还< T> 实施的ICollection< T>。新增

NotSupportedException: There will not be an implementation of the method in this class, by design. This appears several times in virtual methods of a base class, where a derived class is expected to offer an implementation where applicable. It also appears in explicit interface implementation methods (← this is the specific thing the interviewer asked), such as the ReadOnlyCollection<T> implementation of ICollection<T>.Add, etc.

例如,在C#中:

public void MyNotSupportedInterfaceMethod()
{
  throw new NotImplementedException();
}



更新:由于马科斯指出,如果你的类是抽象的,你可以离开实施继承人,但你还是要声明它:

UPDATE: as marcos points out, if your class is abstract, you can leave the implementation to the inheritor, but you still have to declare it:

public abstract class MyClass : ISomeInterface
{
   public abstract void MyNotImplementedInterfaceMethod();
}

这篇关于如何不实现类的接口的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆