Generate Interface from existing class

2019-01-25 01:31发布

I have a class as:

Class MyClass
{
   public MyClass { ... }
   public string Name { get { ... } }
   public int IdNumber { get { ... } set { ... } }
   public void GenerateNme {...}
}

It is just a sample class. I wish to generate Interface from it. Like, MyClass is implementing IMyClass interface. I wish the output to be

public Interface IMyClass
{
   string Name { get; }

   int IdNumber { get; set; }

   void GenerateNumber();
}

and

MyClass : IMyClass
{

}

It can be done manually, but I was just curious to know, is there any other simple method to follow to accomplish this? If not clear, leave a comment.

Thanks.

6条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-25 01:52

Yes, you can extract an interface from a class using Visual Studio:

Inside the target class file: Right Click > Refactor > Extract Interface...

Example

enter image description here

then

enter image description here

查看更多
淡お忘
3楼-- · 2019-01-25 01:52

In Visual Studio 2015, click cursor in or right click on the class name, then select Quick Actions (or press Ctrl-.) and the 'Extract Interface' option shows.

查看更多
聊天终结者
4楼-- · 2019-01-25 01:54

In the refactor menu of visual studio there is an "extract interface" option that does exactly what you describe.

查看更多
贪生不怕死
5楼-- · 2019-01-25 02:08

In Visual Studio 2015/2017/2019, this is under the Quick Actions menu (Ctrl+ period .)

Be sure to put the cursor somewhere in the class name you want to extract the interface from. Otherwise it shows "no quick actions available here".

Note: this is only possible if you can actually extract an interface. For example if your class only has static methods this will not work.

查看更多
放荡不羁爱自由
6楼-- · 2019-01-25 02:08

Ctrl+. was popping up 'generating overrides...' and nothing was happening beyond that so I searched 'refactor' in the quick launch search box. Results had Edit -> Refactor -> Extract Interface (Ctrl+R, Ctrl+I) option.

Hoping, this tip can help someone else too. I am using VS 2017 EE.

查看更多
可以哭但决不认输i
7楼-- · 2019-01-25 02:12

In Visual Studio 2010, you can right-click MyClass and choose Refactor, `Extract Interface..." (Ctrl+R, I). This gives you a window to check the members to be extracted.

查看更多
登录 后发表回答