简体   繁体   中英

Visual Studio dump all properties of class into editor

Ok, here is one for the people that have lots of handy little add ins for visual studio, or can help with a keypress sequence.

Let's say I have a Person class:

class Person
{
    string Name { get; set; }
    int Age { get; set; }
}

And I'm busy coding away happily. I often get the situation where I need to assign values to all the properties of that class, or assign all the values of the properties to something else.

public override void CopyTo(Person myPerson)
{
    myPerson.Name = "XXX";
    myPerson.Age = 11;
}

I would like to generate this part:

myPerson.Name
myPerson.Age

Ie Just dump all the properties of myPerson underneath each other in a little list. In the Visual Studio editor.

I have resharper installed and I had a quick look around for a utility that does specifically this, but I couldn't find one. Anyone can help?

You can use the C# Interactive Window which is part of Visual Studio 2015

> #r "C:/MyApp/bin/Debug/Foo.dll"
> using MyApp;
> var personType = typeof(Person);
> var personProperties = personType.GetProperties();
> foreach(var personProperty in personProperty) { Console.WriteLine($"{nameof(Person)}.{personProperty.Name}"); }

Of course this can be shortened but this shows you how to use it.

Also to setup the project where the class is located, you can right click on Solution Explorer and then select "Initialize Interactive with Project".

All you have to do is print out the object in the Immediate Window of Visual Studio, you don't need R#.

eg ?myPerson

And all your properties will print out just like you want.

类的值列表

Visual Commander有一个示例命令 (3.复制到Visual Studio文本编辑器中所选类的剪贴板属性),您可以进一步自定义场景。

C# Immediate Window is great! This is a one-liner to print out properties in some format needed. Just play with it to suit your needs:

typeof(MyApp.Person).GetProperties().Select(x => x.Name).Aggregate((x, y)=>x +", " +y)

Here is what works for me in Visual Studio 2017:

Open up the Class editor with

Cntrl + Shift + C

then in the Class View window which pops up select the class name which contains the properties you want in the displayed structure. All the properties for the class will be listed in the below window pane. Shift + click the first property then shift + click the last one in the list. Then right click and select the copy option from the popup menu. You can paste from there into Visual Studio. The first paste will look like the following:

Person.Name Person.Age

From there you can just place a carriage return after each property so they end up on separate lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM