ex-18-07

来自「Programming Csharp Source Code(代码) Prog」· 代码 · 共 36 行

TXT
36
字号
// Example 18-07: Dynamically invoking a method

namespace Programming_CSharp
{
   using System;
   using System.Reflection;

   public class Tester
   {
      public static void Main()
      {
         Type theMathType = Type.GetType("System.Math");
         Object theObj = 
            Activator.CreateInstance(theMathType);

         // array with one member
         Type[] paramTypes = new Type[1];
         paramTypes[0]= Type.GetType("System.Double");

         // Get method info for Cos()
         MethodInfo CosineInfo = 
            theMathType.GetMethod("Cos",paramTypes);

         // fill an array with the actual parameters
         Object[] parameters = new Object[1];
         parameters[0] = 45;
         Object returnVal = 
            CosineInfo.Invoke(theObj,parameters);
         Console.WriteLine(
            "The cosine of a 45 degree angle {0}", 
            returnVal);
 
      }
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?