dynamic
来源:互联网 发布:基金从业考试软件 编辑:程序博客网 时间:2024/05/17 05:14
class ExampleClass{ public ExampleClass() { } public ExampleClass(int v) { } public void exampleMethod1(int i) { } public void exampleMethod2(string str) { }}
static void Main(string[] args){ ExampleClass ec = new ExampleClass(); // The following call to exampleMethod1 causes a compiler error // if exampleMethod1 has only one parameter. Uncomment the line // to see the error. //ec.exampleMethod1(10, 4);这样调用报错 dynamic dynamic_ec = new ExampleClass();//这种情况编译时不检查错误 运行时检查错误 // The following line is not identified as an error by the // compiler, but it causes a run-time exception. dynamic_ec.exampleMethod1(10, 4); // The following calls also do not cause compiler errors, whether // appropriate methods exist or not. dynamic_ec.someMethod("some argument", 7, null); dynamic_ec.nonexistentMethod();}任何对象都可隐式转换为动态类型,如下面的示例所示。
dynamic d1 = 7;dynamic d2 = "a string";dynamic d3 = System.DateTime.Today;dynamic d4 = System.Diagnostics.Process.GetProcesses();反之,隐式转换也可动态地应用于类型为 dynamic 的任何表达式。
int i = d1;string str = d2;DateTime dt = d3;System.Diagnostics.Process[] procs = d4;// Valid.ec.exampleMethod2("a string");// The following statement does not cause a compiler error, even though ec is not// dynamic. A run-time exception is raised because the run-time type of d1 is int.ec.exampleMethod2(d1); 参数错误 编译时不会检查因为 dynamic 类型 但是运行时会报错// The following statement does cause a compiler error.//ec.exampleMethod2(7);class Program{ static void Main(string[] args) { dynamic dyn = 1; object obj = 1; // Rest the mouse pointer over dyn and obj to see their // types at compile time. System.Console.WriteLine(dyn.GetType()); System.Console.WriteLine(obj.GetType()); }}WriteLine 语句显示 dyn 和 obj 的运行时类型,此时,两者具有相同的整数类型。 将生成以下输出:
System.Int32
System.Int32若要查看 dyn 和 obj 之间的差异,请在前面示例的声明和 WriteLine 语句之间添加下列两行之间。
dyn = dyn + 3;obj = obj + 3;为尝试添加表达式 obj + 3 中的整数和对象报告编译器错误。 但是,不会报告 dyn + 3 错误。 编译时不会检查包含 dyn 的表达式,原因是 dyn 的类型为 dynamic。
0 0
- dynamic
- @dynamic
- Dynamic
- @dynamic
- dynamic
- dynamic
- dynamic
- @dynamic
- @dynamic
- dynamic-insert,dynamic-update
- dynamic programming
- Dynamic MBean
- Dynamic Menu
- dynamic loading
- dynamic table
- Dynamic Programming
- Dynamic loading
- Dynamic loading
- 快速排序
- 如何修改android工程的包名
- 解决HierarchyViewer无法读取真机应用信息的问题
- 蓝桥杯 算法训练 2的次幂表示
- 零基础openwrt固件编译
- dynamic
- BW十日谈之CUBE(转载)
- XMPP协议实现原理介绍<一>
- 英语字根
- OC-简单的使用BLOCK
- android Fragment 使用
- oracle pl/sql实例练习
- BW十日谈之信息对象(转载)
- hashcode和to_string