C#:表示方法的可执行方式作为接口(interface)的一部分存在

标签 c# interface annotations language-features

在 C# 中有没有办法将方法标记为类的一部分以满足该类实现的接口(interface)?我发现自己有时想知道在挖掘类的代码时为什么会有一些方法,但是当我试图删除一个没有被使用的方法时,我发现有必要让类实现一些接口(interface)。将这些方法标记为这样会很好。类似 @Override annotation 的东西也许是在 Java 中。

编辑:我宁愿显式实现接口(interface),因为这样访问我的类实例上的接口(interface)方法会变得更麻烦(即,必须在调用 MyInterfaceMethod 之前,将 MyClass 的实例转换为 IMyInterface

编辑:我也不希望使用区域。我不希望通过一些任意名称松散地描述一大块代码作为接口(interface)实现的一部分,而是将特定方法表示为接口(interface)的一部分,无论它们在类中的任何位置。即使是一些旨在说明该方法属于哪个接口(interface)的 XML 注释模板也会很好。

编辑: 所有答案似乎都表明我显式实现了我不想做的接口(interface),或者我使用了我也不想做的区域。我想Will最了解我的要求。我希望有类似注释的东西,所以我可以做类似下面的事情:

[Interface(IMyInterface)]
public void MyImplicitlyImplementedInterfaceMethod() { }

或者,正如 dss539 在对 this answer 的评论中提到的那样:

public implement void MyImplicitlyImplementedInterfaceMethod() { }

很像我们今天有 override:public override bool Equals(object obj) { }

最佳答案

你有三个选择:

显式实现接口(interface):

您可以 explicitly implement the interface使用语法 IInterface.MethodName,例如:

bool IInterface.MethodName(string other) 
{
    // code
}

在区域中包装接口(interface)成员

如果您选择通过 UI“实现接口(interface)”,工具已经将您的代码包装在一个区域中:

#region IInterface members

public bool MethodName(string other)
{
    // code
}

#endregion

通过评论记录

C#允许您通过///*XML documentation comments添加多种注释。 .自由使用!

关于C#:表示方法的可执行方式作为接口(interface)的一部分存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2164159/

相关文章:

javascript - WCF 服务 POST 方法不起作用

c# - 将字符串 "7/16/2013 7:00:00 AM"转换为日期时间

unit-testing - Moq-ing 类或接口(interface)有什么区别?

python - 关于使用 Python 扩展对 Dia 进行编程有什么提示吗?

java - 如何避免 swagger codegen 接口(interface)中的默认方法实现?

python - 显示带有注释的图像 - python

c# - C# : how do I use such an attribute? 中的 System.AttributeTargets.GenericParameter

c# - 如何捕获重新抛出的异常?

C#:如何对依赖于同一类中另一个方法的方法进行单元测试?

Java AOP 或 i18n 注释