C#基础:动态查找dynamic

动态查找技术,是为了处理其他语言创建的交互技术。使用dynamic关键字修饰

  1. public class MyClass1
  2.     {
  3.         //参数也可以用dynamic修饰
  4.         public int Add(dynamic var1, dynamic var2) => var1 + var2;//浪漫哒表达式
  5.     }
  6.     public class MyClass2 { }
  7.  
  8. public class Program{
  9.         static int callCount = 0;
  10.         static dynamic GetValue() {//动态查找方法
  11.             if (callCount++ == 0)
  12.             {
  13.                 return new MyClass1();
  14.             }
  15.                 return new MyClass2();            
  16.         }
  17.  
  18.      public static void Main(string[] args){
  19.               try
  20.               {//MyClass2是空的,没有Add方法,此处会出现异常
  21.                 dynamic firstResult = GetValue();
  22.                 dynamic secondResult = GetValue();
  23.                 Console.WriteLine($"{firstResult.ToString()}");
  24.                 Console.WriteLine(secondResult.ToString());
  25.                 Console.WriteLine(firstResult.Add(2, 5));
  26.                 Console.WriteLine(secondResult.Add(2, 5));
  27.             }
  28.             catch (RuntimeBinderException e)
  29.             {
  30.                 Console.WriteLine(e.Message); ;
  31.             }
  32.       }
  33. }

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/84403997
今日推荐