深入探究 C# 动态类型与动态语言运行时
1. 动态变量的特性
动态变量与隐式声明或通过 System.Object 引用声明的变量有很大不同,它不是强类型的,即动态数据不是静态类型。在 C# 编译器看来,使用 dynamic 关键字声明的数据点可以被赋予任何初始值,并且在其生命周期内可以重新赋值为任何新的(可能不相关的)值。
以下是一个示例方法及其输出:
static void ChangeDynamicDataType()
{
// 声明一个名为 't' 的动态数据点
dynamic t = "Hello!";
Console.WriteLine("t is of type: {0}", t.GetType());
t = false;
Console.WriteLine("t is of type: {0}", t.GetType());
t = new List<int>();
Console.WriteLine("t is of type: {0}", t.GetType());
}
输出结果:
t is of type: System.String
t is of type: System.Boolean
t is of type: System.Collections.Generic.List`1[System.Int32]
超级会员免费看
订阅专栏 解锁全文
951

被折叠的 条评论
为什么被折叠?



