在 Visual Studio 中实例化对象的快捷方式

Shortcut to instantiate an object in Visual Studio

我有一个class,它有8个以上的属性,我经常想用一些方法来实例化它,但是必须一个一个地写属性给它们赋值,超级繁琐。

有没有什么办法可以用快捷键插入一种"code fragment",这样我就可以插入class的实例,而我只要修改一下值就可以添加了? .

我不想使用构造函数,因为我希望实例对于我的代码 reader 是可读的,并且因为构造函数在 LinQ 中不起作用 SQL.

我使用 Visual Studio 2015,C#,Resharper。

非常感谢。

如果你这样初始化:

  var example = new Example()
    {
        ...
    };

然后您可以使用 Ctrl-Space,它将继续为您提供尚未设置的自动完成属性。

据我所知,没有内置的方法来生成具有对象所有属性的实例化器。通常当你必须这样做时,你会通过一个构造函数,这样你就知道对象被正确创建了。

您可以在 Visual Studio 中创建某种类型的代码片段,但您必须自己制作它,并且它只对那个对象有效....

您也可以查看此 post,因为它非常接近您要查找的内容,但听起来他们也没有找到执行此操作的好方法:Is there a way, at design time, to initialize an object with all properties in Visual Studio 2010?

您可以创建自定义代码片段,格式如下:

<?xml version="1.0" encoding="utf-8" ?> <CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <Header> <Title>Create instance of my class</Title> <Author>Author</Author> <Shortcut>ShortCut (then press tab tab)</Shortcut> <-- Put your snippet <Description>Description</Description> <SnippetTypes> <SnippetType>SurroundsWith</SnippetType> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>message</ID> <Default>my function</Default> </Literal> </Declarations> <Code Language="CSharp"> <![CDATA[ var myclass = new MyClass() { Property1 = 1, Property2 = 2 }; ]]> </Code> </Snippet> </CodeSnippet>

您可以将其保存在 Nodepad 中,并且必须使用 .snippet 扩展名保存此文件。查找文件夹 ..Visual Studio 2017\Code Snippets\Visual C#\My Code Snippets
当你准备好打开 VS 并进入 Tools -> Code Snippet Manager 并选择 Language CSharp 然后 select 你的代码片段来自我的代码片段文件夹,你应该准备好使用它了

我已经创建了 Generate an initializer for a new object with names of public properties and fields command for the Visual Commander 扩展。输入 class 名称后调用它,它会生成一个初始化程序: