Is there a ToString() generator available in Visual Studio 2010?

前端 未结 11 742
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 17:39

Is there any way to generate a ToString() using Visual Studio 2010?

I really don\'t want to do this by hand!

[EDIT]

I\'m looking for a s

相关标签:
11条回答
  • 2021-01-03 18:25

    Major pain that VS 2010 doesn't even have an autogenerate ToString method, syntax is close enough to Java where I used Ecilpse to Generate the ToString and then pasted it into VS...

    0 讨论(0)
  • 2021-01-03 18:32

    Maybe you should take a look at AutoCode 4.0. It is a Visual Studio extension which will brings some snippets with it.

    For example you could somewhere within your class simply write tostr and press Ctrl+Enter and it will automatically generate the ToString() method that concatenates all public properties of the class.

    0 讨论(0)
  • 2021-01-03 18:34

    It doesn't exist on VS out of the box, but it does on the ReSharper plugin, if you don't want to implement it yourself. The plugin is commercial, but I personally think it is worth the money.

    With ReSharper, it would be alt+ins -> overriding members -> tostring while class name is on the cursor.

    0 讨论(0)
  • 2021-01-03 18:34

    If you need better representation of your object while debugging you can use the DebuggerDisplayAttribute:

    [DebuggerDisplay("Count = {count}")]
    class MyHashtable
    {
        public int count = 4;
    }
    

    This can be quicker than overriding ToString, but it still doesn't let you choose fields, you have to type them.

    0 讨论(0)
  • 2021-01-03 18:35

    With Reflection you can actually code a ToString() method:

    public override String ToString()
    {
        Type objType = this.GetType();
        PropertyInfo[] propertyInfoList = objType.GetProperties();
        StringBuilder result = new StringBuilder();
        foreach (PropertyInfo propertyInfo in propertyInfoList)
             result.AppendFormat("{0}={1} ", propertyInfo.Name, propertyInfo.GetValue(this));
    
         return result.ToString();
    }
    
    0 讨论(0)
提交回复
热议问题