简体   繁体   English

如何在C#中自动实现接口?

[英]How do you auto-implement an interface in C#?

Previously in Visual Studio, if you declared a class with an interface you could put your cursor on the interface, right-click it and select Implement Interface . 以前在Visual Studio中,如果您声明了一个带接口的类,您可以将光标放在接口上,右键单击它并选择实现接口 ( See here for a similar question for VS 2008.) 有关 VS 2008的类似问题, 请参阅此处 。)

I've started working on a project that has defined numerous interfaces that will be used with SimpleInjector. 我已经开始研究一个已经定义了许多将与SimpleInjector一起使用的接口的项目。 Now, as I am beginning to write my service classes, I've noticed that the Implement Interface menu option is gone. 现在,当我开始编写服务类时,我注意到实现接口菜单选项已经消失。

How can I implement all necessary method stubs like I could in VS 2008? 如何在VS 2008中实现所有必要的方法存根?

Sorry if this is a duplicate, however, I couldn't find this answer anywhere. 很抱歉,如果这是重复的,我无法在任何地方找到这个答案。


EDIT NOTES - Aug 17, 2018 编辑笔记 - 2018年8月17日

This has been a hot question over the years. 多年来,这一直是一个热门话题。 I've updated the title and tags for this so that it covers all pertinent versions of C# and Visual Studio. 我更新了标题和标签,以便它涵盖C#和Visual Studio的所有相关版本。

This was ultimately a coder FAIL on my part. 这对我来说最终是一个编码器失败。 Much like classes, interfaces when generated by VS aren't defined as public . 很像类,VS生成的接口未定义为public You will have to manually modify the interface declaration with the public accessor since VS doesn't automatically add it. 您必须使用public访问器手动修改接口声明,因为VS不会自动添加它。 It's easy to forget this step because you don't have to set member modifiers within the interface since, by definition, they will all be public . 很容易忘记这一步,因为您不必在界面中设置成员修饰符,因为根据定义,它们都将是public

That hasn't changed. 这没有改变。 All you need to do is hover over the interface name in the class, and the blue underline bar should show up, giving you options to implement the interface. 您需要做的就是将鼠标悬停在类中的接口名称上,并显示蓝色下划线栏,为您提供实现接口的选项。 If the blue underline is not appearing, check to make sure the interface is accessible with what assemblies and namespaces you are referencing. 如果没有出现蓝色下划线,请检查以确保可以使用您引用的程序集和名称空间访问该接口。

When you look at the interface name, you should see a little blue underline: 当您查看界面名称时,您应该看到一个蓝色的下划线:

第一张图片

If you hover over it, a drop down menu will appear, letting you implement the interface: 如果将鼠标悬停在上面,则会出现一个下拉菜单,让您实现界面:

第二张图片

将光标放在界面文本中(冒号后面的部分)并按Ctrl +。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM