gpt4 book ai didi

c# winform 在运行时检查对象

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:31 24 4
gpt4 key购买 nike

我想在运行时在 GUI 中显示任意对象的公共(public)属性/值。

是否有一个 winform 允许用户像在 Debug模式下一样查看任何对象的内容?该对象将包含许多词典 > 并且能够在运行时扩展和查看这些列表的内容会很好。

如果不可用,是否有办法实现类似的目标?

谢谢

最佳答案

您需要做的就是创建一个带有 PropertyGrid 的表单。然后设置选中的对象。

enter image description here

using xxx.CFM.UI.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace xxx.CFM.UI.Forms
{
/// <summary>
/// Form used to inspect objects at runtime
/// </summary>
public partial class frmInspector : BaseForm
{
#region Properties

/// <summary>
/// Gets or Sets the
/// </summary>
public object SelectedObject
{
get { return propertyGrid.SelectedObject; }
set { propertyGrid.SelectedObject = value; }
}

#endregion Properties

#region Constructor

/// <summary>
/// Constructor
/// </summary>
public frmInspector(object objectToInspect)
{
try
{
InitializeComponent();

this.SelectedObject = objectToInspect;
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}

#endregion Constructor

#region Events

/// <summary>
/// Closes the form
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void btnClose_Click(object sender, EventArgs e)
{
try
{
this.Close();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}

#endregion Events
}
}

例如,我在网格中的上下文菜单上使用它来期望它下面的数据记录:

 /// <summary>
/// Opens the object inspector
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void inspectorMenuItem_Click(object sender, EventArgs e)
{
try
{
//Get the payload
SectionDataTreeListMenuItemPayload payload = (sender as ToolStripMenuItem).Tag as SectionDataTreeListMenuItemPayload;

if (payload == null || payload.DataRow == null)
return;

using (frmInspector frmInspector = new frmInspector(payload.DataRow))
frmInspector.ShowDialog();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}

您可以做的另一个小技巧是确保表单仅在 Debug模式下构建时可用,方法是使用以下代码和“编译器指令”。 (当然,如果你希望它只用于调试)

#if DEBUG

//Add object inspector menu item if built in debug mode
ToolStripMenuItem inspectorMenuItem = new ToolStripMenuItem();
inspectorMenuItem.Text = "Inspect Object";
inspectorMenuItem.Image = Properties.Resources.Inspect24x24;
inspectorMenuItem.Click += inspectorMenuItem_Click;
inspectorMenuItem.Tag = payload;
contextMenuStrip.Items.Add(inspectorMenuItem);

#endif

关于c# winform 在运行时检查对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30910353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com