正如主题所暗示的那样,我对 PropertyInfo.SetValue 有一些问题。言归正传,这是我的例子——我创建了自己的类,它的主要内容是演示对象:
using System;
using System.Reflection;
namespace TestingSetValue
{
public class Link
{
private object presentationObject = null;
private string captionInternal = string.Empty;
public Link (string caption)
{
captionInternal = caption;
}
public string CaptionInternal
{
get { return captionInternal; }
set { captionInternal = value; }
}
public bool Visible
{
get
{
if (PresentationObject != null)
{
PropertyInfo pi = PresentationObject.GetType().GetProperty("Visible");
if (pi != null)
{
return Convert.ToBoolean(pi.GetValue(PresentationObject, null));
}
}
return true;
}
set
{
if (PresentationObject != null)
{
PropertyInfo pi = PresentationObject.GetType().GetProperty("Visible");
if (pi != null)
{
pi.SetValue(PresentationObject, (bool)value, null);
}
}
}
}
public object PresentationObject
{
get { return presentationObject; }
set { presentationObject = value; }
}
}
}
然后,我这样做:
private void btnShowLink_Click(object sender, EventArgs e)
{
Link link = new Link("Here I am!");
this.contextMenu.Items.Clear();
this.contextMenu.Items.Add(link.CaptionInternal);
link.PresentationObject = this.contextMenu.Items[0];
link.Visible = true;
lblCurrentVisibility.Text = link.Visible.ToString();
}
现在,我可以想象这看起来不太合乎逻辑/经济,但它显示了我真正问题的本质。即,在我调用后,为什么演示对象的可见性(以及 link.Visible 的值)没有改变:
link.Visible = true;
我根本不知道还能做些什么来完成这项工作......任何帮助都深表感谢。
为了让事情变得更有趣,属性 Enabled 的行为符合它的预期......
PropertyInfo pi = PresentationObject.GetType().GetProperty("Enabled");
是否与 Visible 实际上是 ToolStripDropDownItem 基础基础对象的属性,而 Enabled 是 ToolStripDropDownItem 的“直接”属性这一事实有关?