How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

前端 未结 12 1816
有刺的猬
有刺的猬 2020-11-27 12:54

I\'ve gotten accustomed to many of the Java IDEs (Eclipse, NetBeans, and IntelliJ IDEA) providing you with a command to generate a default constructor for a class based on t

12条回答
  •  Happy的楠姐
    2020-11-27 13:37

    C# added a new feature in Visual Studio 2010 called generate from usage. The intent is to generate the standard code from a usage pattern. One of the features is generating a constructor based off an initialization pattern.

    The feature is accessible via the smart tag that will appear when the pattern is detected.

    For example, let’s say I have the following class

    class MyType { 
    
    }
    

    And I write the following in my application

    var v1 = new MyType(42);
    

    A constructor taking an int does not exist so a smart tag will show up and one of the options will be "Generate constructor stub". Selecting that will modify the code for MyType to be the following.

    class MyType {
        private int p;
        public MyType(int p) {
            // TODO: Complete member initialization
            this.p = p;
        }
    }
    

提交回复
热议问题