Skip to content

C# dynamic & var

L edited this page Mar 19, 2020 · 2 revisions

摘抄自C# 动态绑定C# var

动态绑定会将类型,成员和操作的解析过程从编译时延迟到运行时
使用上下文关键字 dynamic 声明动态类型

字段,属性,方法,事件,构造函数,索引器,运算符和转换都可以动态调用
动态类型具有来自所有其他类型的隐式转换

int i = 7;
dynamic d = i;
long j = d; // No cast required (implicit conversion)

要使转换成功,动态对象的运行时类型必须可隐式转换为目标静态类型。
以下示例会抛出RuntimeBinderException,因为int不能隐式转换为short:

int i = 7;
dynamic d = i;
short j = d; // throws RuntimeBinderException

var vs dynamic

var 使编译器找出类型,本身类型是确定的,编译器可以从初始化表达式推断类型
dynamic使运行时确定类型

dynamic x = "hello"; // Static type is dynamic, runtime type is string
var y = "hello";     // Static type is string, runtime type is string
Clone this wiki locally