昨日同事用 VB.net 2002 寫了一段反射的代碼,結果怎麼都無法在運行時獲得成員變數!我看過,覺得代碼應該沒問題,便用 C#(VS.net 2003) 重寫,結果成功。附C#代碼如下:
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
public Form1()
{
// Windows 表單設計器支援所必需的
InitializeComponent();
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
// set properties value...
}
private void Form1_Click(object sender, System.EventArgs e)
{
System.Reflection.FieldInfo field = this.GetType().GetField("button1", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
System.Windows.Forms.Control ctl = (Control)field.GetValue(this);
MessageBox.Show(ctl.Text + System.Environment.NewLine + ctl.Name);
}
}
那麼為什麼在C#中可以,而在VB.net中卻始終無法獲得 "button1" 的 System.Reflection.FieldInfo 對象呢?
使用 this.GetType().GetFields()【VB.net 中為 Me.GetType().GetFields()】枚舉所有成員欄位,結果發現原本為 "button1" 的控制項名變成了 "_button1" 了!!!怎麼會多出一個首碼的底線???!!!是不是VB.net編譯器搞的鬼?!唉,把 Form1_Click 事件處理函數中的第一行代碼中的 "button1" 改為 "_button1" 後,成功!