首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

代码看不懂, 求解释,关于反射,该怎么处理

2012-05-11 
代码看不懂, 求解释,关于反射C# codeusing Systemusing System.Reflectionpublic class AssemblyDemo{pu

代码看不懂, 求解释,关于反射

C# code
using System;using System.Reflection;public class AssemblyDemo{    public static void Main(string[] args)    {        int i,j;        if (args.GetLength(0) < 1)        {            Console.WriteLine("usage is AssemblyDemo < library_name >");        }        else        {            Assembly assembly = Assembly.LoadFrom(args[0]);            Type[] types = assembly.GetTypes();            Console.WriteLine(assembly.GetName().Name + " contains the following  types");            for (i = 0 ; i < types.GetLength(0); ++i)            {                Console.WriteLine("\r(" + i + ") " + types[i].Name);            }            i = types.Length - 1;            Console.Write("make selection(0-" + i + "):");            j = Convert.ToInt32(Console.ReadLine());            Console.WriteLine();            if (types[j].IsSubclassOf(typeof(Sport)))            {                ConstructorInfo ci = types[j].GetConstructor(new Type[0]);                Sport sport = (Sport)ci.Invoke(new Object[0]);                Console.WriteLine(sport.GetName() + " has "  + sport.GetDuration());               }            else            {                Console.WriteLine(types[j].Name + " is not a sub-class of Sport");            }        }    }}


上面代码中

 
C# code
             ConstructorInfo ci = types[j].GetConstructor(new Type[0]);                Sport sport = (Sport)ci.Invoke(new Object[0]);


这两句中的 new Type[0] 和 new Object[0] 真的 不明白, 求明白的同学帮忙讲讲, 多谢了

[解决办法]
Type.GetConstructor Method (Type[]) 因为方法的签名是type的数组,所以ConstructorInfo ci = types[j].GetConstructor(new Type[0]);这里给了一个空的数组,意思就是获取Sport类的无参构造函数。

 Sport sport = (Sport)ci.Invoke(new Object[0]);意思是调用这个构造函数,因为是无参的构造函数,当然是给一个空的Object数组啦。

热点排行