码迷,mamicode.com
首页 > Windows程序 > 详细

c# 反射时GetType方法查找Type的分析

时间:2016-11-23 19:09:41      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:nbsp   tools   net   没有   mod   src   rac   包含   分析   

反射是高级语言里面很强大的一种机制。C#也给我们提供了强大的反射机制。反射使用起来非常简单,最常见的步骤是:

1,定义一个Type 对象, Type myType;

2,通过字符串或者其它流初始化该对象,MyType = Type.GetType("MyClass");

 

在Type.GetType()方法执行时,系统怎么根据字符串查找正确的类的定义呢?看下面代码

 

[c-sharp] view plain copy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Reflection;  
  4. using System.IO;  
  5.   
  6. namespace Test{  
  7. public delegate Object TwoInt32s(Int32 n1, Int32 n2);  
  8. public delegate Object OneString(String s1);  
  9.   
  10.   
  11. class App  
  12. {  
  13.     public static void Main(String[] args)  
  14.     {  
  15.         //Type delType = Type.GetType("TwoInt32s");//错误的调用方法  
  16.         Type delType = Type.GetType("Test.OneString");//正确的调用方法  
  17.         if (delType == null)  
  18.         {  
  19.             Console.WriteLine("Invalid delType argument: " + "TwoInt32s");  
  20.             return;  
  21.         }  
  22. }  
  23. }  
  24. }  

 

这段代码说明Type.GetType在解析类型的时候如果参数字符串没有指定namespace将会导致程序不能正确解析类型。

 

如果我们把namespace去掉,得到下面的代码

 

[c-sharp] view plain copy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Reflection;  
  4. using System.IO;  
  5.   
  6. public delegate Object TwoInt32s(Int32 n1, Int32 n2);  
  7. public delegate Object OneString(String s1);  
  8.   
  9.   
  10. class App  
  11. {  
  12.     public static void Main(String[] args)  
  13.     {  
  14.          
  15.         Type delType;  
  16.         delType = Type.GetType("System.IO.File");//正确方法  
  17.          //delType = Type.GetType("File");//错误   
  18.        delType = Type.GetType("TwoInt32s");//正确的调用方法  
  19.         //Type delType = Type.GetType("Test.OneString");  
  20.         if (delType == null)  
  21.         {  
  22.             Console.WriteLine("Invalid delType argument: " + "TwoInt32s");  
  23.             return;  
  24.         }  
  25. }  
  26. }  
技术分享

 

 

这说明如果某类型被包含在namspace里面就必须要用包含namespace的完整路径来获取类型信息。

c# 反射时GetType方法查找Type的分析

标签:nbsp   tools   net   没有   mod   src   rac   包含   分析   

原文地址:http://www.cnblogs.com/sylone/p/6094759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!