淺淡反射問題
[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的工具出來。