开发者

Visual Studio 2010: Easiest way to duplicate a class?

开发者 https://www.devze.com 2023-02-11 04:28 出处:网络
Is there an easy way to duplicate a开发者_开发知识库 class with a different name?Not sure whether this can be qualified as the easiest way but if you have ReSharper, you can use its Copy Type refactor

Is there an easy way to duplicate a开发者_开发知识库 class with a different name?


Not sure whether this can be qualified as the easiest way but if you have ReSharper, you can use its Copy Type refactoring to copy classes/interfaces/structs with control over the namespace the copy is landing in and naming within the copy - which means that if you're copying a class with 5 constructors, the copy will have all of them renamed to match the name of the new class.

However, depending on what you're trying to achieve, using Extract Interface or Extract Superclass might be a better option.


No, there's no refactoring tool for duplicating a class but with different name.

I would imagine that the reason why this feature is not present is because duplicating code is generally considered a bad idea. I'd suggest instead changing your class into a base class and then make two derived classes from it, overriding methods where you need to change the behaviour.


Refactor to give a new name, copy, undo, paste :-) Remember the undo! This will rename the constructors and finalizers!


  • Open file in Visual Studio.
  • Press Ctrl+A.
  • Press Ctrl+C.
  • Create a new file for the new class.
  • Press Ctrl+V in the new file.
  • Replace all old class names with the new one. (Ctrl+H)


First of all: now there is the option of "Copy Class" with the MS powertools for VS (marketplace)

Second: to all the critics that know better - there are legitimate cases where you want to copy a class as a starting point. I for example have a base class and from it I derive dozens of classes with different implementations, yet I do have a "reference class" derived from the base which already contains the overides, comments, etc. so I do not have to repeat the same over and over again. This is just one of the many situation where you want to copy a class.


It's usually better to refactor your class to be reusable. Copy paste code leads to having to fix the same code in multiple places and much pain as you're breaking OO principles.


Copy and paste and give the class a new name ?

It is generally not a good idea just to copy code and give it a new class name. It appears you may want something to do with inheritance / interfaces?

How about creating a base class and then use that base class for further classes that have the same / close to the same functionality.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号