正如主題所示,我在PropertyInfo.SetValue中遇到了一些問題。要到這一點,這是我的例子 - 我創造我自己的類和它的主要的是表現對象:.NET 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;
我根本不知道該做些什麼,使這項工作...任何幫助深受讚賞。
爲了讓事情更有趣,物業已啓用的行爲與預期的吧...
PropertyInfo pi = PresentationObject.GetType().GetProperty("Enabled");
難道是相關的事實,可見實際上是ToolStripDropDownItem基地的基礎對象的屬性,而啓用是ToolStripDropDownItem的'直接'屬性嗎?
謝謝,非常感謝,非常感謝!我只是將「可見」改爲「可用」,現在一切正常 - 噢,快樂:)現在,認真搜索哪個關鍵字來找到這個有趣的信息/概念? – NETFrameworkEnthusiast
@NETFrameworkEnthusiast - 我去了MSDN頁面的ToolStripItem.Visible屬性的定義http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripitem.visible.aspx,並看到評論在最底層。我還在Reflector中查看了這個屬性,發現它並沒有以標準的對稱方式實現 –