【问题标题】:List all public class properties and fields at design time in Visual Studio在 Visual Studio 中的设计时列出所有公共类属性和字段
【发布时间】:2011-08-29 13:10:22
【问题描述】:

是否可以在 Visual Studio IDE 中获取一个类型的所有公共成员的列表?

在编写测试时,我经常需要将类/结构中的所有公共字段/设置器设置为某个值。

如果我能打字最好:

MyType x = new MyType();

然后自动生成类似

的东西
x.StrProp = "StrProp";
x.IntProp = 0;
x.DtProp = DateTime.Now;
x.OtherProp = new Othertype()

但是仅仅获取一个列表然后使用列编辑会很有帮助

编辑: 发现用宏做起来并不难

【问题讨论】:

    标签: c# visual-studio-2010 ide code-generation


    【解决方案1】:

    如何启动调试会话,在开始时中断,然后调用类似的东西

    typeof(System.Windows.Forms.Control)
        .GetProperties(System.Reflection.BindingFlags.Public | 
            System.Reflection.BindingFlags.Instance)
    

    在即时窗口中? :)

    结果是这样的:

    {System.Reflection.PropertyInfo[0x0000004a]}
        [0x00000000]: {System.Windows.Forms.AccessibleObject AccessibilityObject}
        [0x00000001]: {System.String AccessibleDefaultActionDescription}
        [0x00000002]: {System.String AccessibleDescription}
        [0x00000003]: {System.String AccessibleName}
        [0x00000004]: {System.Windows.Forms.AccessibleRole AccessibleRole}
        [0x00000005]: {Boolean AllowDrop}
    

    很遗憾,您不能在即时窗口中使用 lambda 表达式 - 这可以让您更轻松地以更容易的格式获取属性。但是,我建议编写一个非常简单的工具来加载您的程序集,让您选择类型并以所需的格式输出代码(和/或将其复制到剪贴板或 VS 编辑器中)。该工具至少可以完全满足您的需求。然后配置工具,例如作为 Visual Studio 中的外部工具,可以更轻松地与当前项目一起运行。

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 2011-03-18
      • 2015-06-02
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      相关资源
      最近更新 更多