淺淡反射問題

來源:互聯網
上載者:User

淺淡反射問題
[Key word:convert string to variable,C#,Reflection]
  在學習反射的時候,總有人跟我說,沒有必要去學習一些又難又沒用的東西。然而今天我先不說反射可以為我們解決什麼問題(其實我也不清楚),從一個實際的問題出發來簡單的討論一下反射問題。

有這樣的一個實際問題,兩個變數:
string m_str1 = "m_str2";
string m_str2 = "This is a test!";
現在的問題:如何利用m_str1得到"This is a tset!"(不能用m_str2),也就是說,如何讓m_str1裡的值成為一個新的變數。

在此之前,我找了到了幾個有解決方案的網站,得其中一個的啟示,用到了反射。這裡是網址:
http://www.experts-exchange.com/M_3562622.html
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2005-04/msg03271.html

解決樣本(Code):

using System;
using System.Reflection;
using System.Security;

public class Sample
{
    static public string m_str1    = "This is a test!";
    static public string m_str2    = "m_str1";


    unsafe public static void Main()
    {
        FieldInfo m_field    = Type.GetType("Sample").GetField(m_str2);
        Console.WriteLine(m_field.GetValue(m_str2));
}
}

實際應用:
  在實際的項目中,我遇到這樣的一個問題,我在一個類裡添加很多靜態字串做為資源,有一些很長,但很一個都按結構分好了類,在類名為:WaveTextManager裡,其中有一些提示使用者操作錯誤的字串。那麼當使用者操作錯誤的時候,把使用者匯入到錯誤頁面上,然後根據參數來選擇提示資訊。部份代碼:

        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            string m_msgType            = Request["ErrorType"];
            WaveTextManager.ErrorMsg m_errorType    = new WaveTextManager.ErrorMsg();
            if(m_msgType==null)return;
            FieldInfo m_errorField        = m_errorType.GetType().GetField(m_msgType);
            if(m_errorField==null)return;
            string m_errorMsg            = m_errorField.GetValue("Webb.WAVE.Controls.ErrorMsg").ToString();
            if(m_errorMsg==null)return;
            Response.Write(m_errorMsg);
        }

好了,這裡只是簡單的利用一個實際問題來討論一下反射問題,在理論上,可以用反射來完成一個類似ILDasm的工具出來。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.