大家好!
刚才快下班的时候我正在写一个winform的程序,界面是treeview+listview的联动,就好像windows的组策略的样子,在子窗体中修改策略的安全设置,在主窗体中刷新显示,见下图:

一想,不就是子父窗体传值吗,我以前做过啊,还写过两篇教程呢。
c#,winform,show,showdialog,子窗体,父窗体,传值,输入正确
winform+c#之窗体之间的传值
就开始写了,就利用属性和构造函数吧,定义属性,添加构造函数。。。。
咦,在主窗体的代码里面怎么也点不出来子窗体的属性了,怎么回事呢,把教程找出来看了一下,没有问题,删除重写,还是不行。重启vs2005,还是不行,重启电脑,还是不行,恩,排除了这些怪异原因。
我仔细看了一下,有点不一样了,教程的传值,子窗体是new出来的,可是我这里用的是反射,根据双击的名字反射出来的,就好像教程
通过双击listview中的项目来打开新窗体,有点像组策略中的双击一条策略,然后弹出相应的窗体,修改策略
,这就是不一样了,我就想了,是不是因为反射出来的东西,反射吗,本来就是要在运行的时候动态的访问,在编译的时候,甚至在写代码的时候是根本访问不到的,要不也不叫动态创建,反射了。
那怎么办呢,我就想了,窗体反射,反射不是可以查看类型的内部吗,可以了解类型的成员,属性,方法,连私有的都可以访问得到啊,对了,就是用反射,用反射来获取刚才写的属性就可以了。
说干就干,主窗体代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace WindowsApplication1


{
public partial class frmPolicyConfig : Form

{
public frmPolicyConfig()

{
InitializeComponent();
}
private string returnValue;
public string ReturnValue

{

get
{ return this.returnValue; }

set
{ listView1.SelectedItems[0].SubItems[2].Text = value; }
}
private void listView1_DoubleClick(object sender, EventArgs e)

{
Type type = Type.GetType("WindowsApplication1." + listView1.SelectedItems[0].SubItems[2].Text);
object obj = Activator.CreateInstance(type);
Form form = (Form)obj;
form.Owner = this;
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)

{
PropertyInfo[] pinfos = type.GetProperties();
foreach (PropertyInfo p in pinfos)

{
if (p.Name == "PasswordLength")

{
//MessageBox.Show(Convert.ToString(p.GetValue(obj, null)));
this.returnValue=Convert.ToString(p.GetValue(obj, null))+" 个字符";
listView1.SelectedItems[0].SubItems[1].Text = this.returnValue;

//foreach (ListViewItem lvItem in listView1.Items)
//{
// if (lvItem.Text.Equals("密码长度最小值"))
// {
// lvItem.SubItems[1].Text = this.returnValue;
// break;
// }
//}
break;
}
}
}
}

}
}
子窗体的代码如下,测试通过
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1


{
public partial class frmPasswordLength : Form

{

public frmPasswordLength()

{
InitializeComponent();
button2.DialogResult = DialogResult.OK;
button1.DialogResult = DialogResult.Cancel;
}
public int PasswordLength

{

get
{ return Convert.ToInt32( this.numericUpDown1.Value); }

set
{ this.numericUpDown1.Value = value; }
}

}
}
修改成功

大功告成,希望对大家有帮助,谢谢大家耐心看完我的教程。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构