浅淡反射问题

本文从实际问题出发探讨C#反射问题。以将字符串转换为变量为例,介绍了利用反射解决该问题的思路,并给出相关参考网址。还提及在实际项目中,在类里添加静态字符串资源,根据参数选择提示信息的应用,理论上可用反射完成类似ILDasm的工具。

浅淡反射问题
[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):

None.gif using  System;
None.gif
using  System.Reflection;
None.gif
using  System.Security;
None.gif
None.gif
public   class  Sample
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static public string m_str1    = "This is a test!";
InBlock.gif    
static public string m_str2    = "m_str1";
InBlock.gif
InBlock.gif
InBlock.gif    
unsafe public static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        FieldInfo m_field    
= Type.GetType("Sample").GetField(m_str2);
InBlock.gif        Console.WriteLine(m_field.GetValue(m_str2));
ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

实际应用:
  在实际的项目中,我遇到这样的一个问题,我在一个类里添加很多静态的字符串做为资源,有一些很长,但很一个都按结构分好了类,在类名为:WaveTextManager里,其中有一些提示用户操作错误的字符串。那么当用户操作错误的时候,把用户导入到错误页面上,然后根据参数来选择提示信息。部份代码:

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

好了,这里只是简单的利用一个实际问题来讨论一下反射问题,在理论上,可以用反射来完成一个类似ILDasm的工具出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值