C#:表示方法的可执行方式是接口的一部分 [英] C#: enforceable way of signifying a method is there as part of interface

查看:17
本文介绍了C#:表示方法的可执行方式是接口的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way in C# to mark a method as being part of a class to satisfy an interface that the class implements? I find myself wondering sometimes when digging in a class's code why some methods are there but then, when I try to remove one since it isn't in use, I see it's necessary in order for the class to implement some interface. It'd be nice to have these methods marked as such. Something like the @Override annotation in Java, maybe.

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

I would prefer to not explicitly implement the interface because then accessing the interface methods on an instance of my class becomes more of a hassle (i.e., having to cast an instance of MyClass to be IMyInterface before calling MyInterfaceMethod).

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

I would also prefer not to use regions. I don't want a big block of code described loosely through some arbitrary name as being part of an interface implementation, but rather to denote specific methods, wherever they may be within the class, as being part of an interface. Even some XML comment template that's intended for saying which interface the method belongs to would be nice.

所有的答案似乎都表明我明确实现了接口,我不想这样做,或者我使用了区域,我也不想这样做.我认为理解我的要求最好.我希望有一个注释之类的东西,所以我可以做如下的事情:

All the answers seem to suggest I explicitly implement interfaces, which I don't want to do, or that I use regions, which I also don't want to do. I think Will understood my request best. I was hoping for something like an annotation, so I could do something like the following:

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

或者,正如 dss539 在对 这个答案:

Or, as dss539 mentioned in a comment to this answer:

public implement void MyImplicitlyImplementedInterfaceMethod() { }

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

推荐答案

您有三个选择:

显式实现接口:

您可以显式实现接口使用语法 IInterface.MethodName,例如:

You can explicitly implement the interface using the syntax IInterface.MethodName, for example:

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

将界面成员包装在一个区域中

如果您选择通过用户界面实现接口",工具已经将您的代码包装在一个区域中:

Tools will already wrap your code in a region if you choose to "Implement an interface" through the UI:

#region IInterface members

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

#endregion

通过评论记录

C# 允许您通过 ///*XML 文档注释.大量使用!

C# allows you to add multiple kinds of comments through //, /*, or XML documentation comments. Use liberally!

这篇关于C#:表示方法的可执行方式是接口的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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