如何使用 Visual Studio(和/或 ReSharper)从类字段生成构造函数? [英] How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?
问题描述
我已经习惯了许多 Java IDE(Eclipse,NetBeans 和 IntelliJ IDEA) 为您提供了一个命令,用于根据类中的字段为类生成默认构造函数.
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 the fields in the class.
例如:
public class Example
{
public decimal MyNumber { get; set; }
public string Description { get; set; }
public int SomeInteger { get; set; }
// ↓↓↓ This is what I want generated ↓↓↓
public Example(decimal myNumber, string description, int someInteger)
{
MyNumber = myNumber;
Description = description;
SomeInteger = someInteger;
}
}
让构造函数填充对象的所有字段是大多数 OOP 语言中的一项常见任务,我假设有一种方法可以节省我在 C# 中编写此样板代码的时间.我是 C# 世界的新手,所以我想知道我是否遗漏了有关该语言的一些基本知识?Visual Studio 中是否有一些显而易见的选项?
Having a constructor populate all of the fields of an object is such a common task in most OOP languages, I'm assuming that there is a some way for me to save time writing this boilerplate code in C#. I'm new to the C# world, so I'm wondering if I'm missing something fundamental about the language? Is there some option in Visual Studio that is obvious?
推荐答案
ReSharper 提供了一个 生成构造函数工具,您可以在其中选择要初始化的任何字段/属性.我使用 Alt + Ins 热键来访问它.
ReSharper offers a Generate Constructor tool where you can select any field/properties that you want initialized. I use the Alt + Ins hot-key to access this.
这篇关于如何使用 Visual Studio(和/或 ReSharper)从类字段生成构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!