VB.net 的反射疑惑

來源:互聯網
上載者:User

  昨日同事用 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" 後,成功!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.