C#中var和dynamic的区别

C#中var和dynamic的区别

隐式类型局部变量 – var 是那些在未明确指定 .NET 类型的情况下声明的变量。在隐式类型变量中,变量的类型在编译时由编译器从用于初始化变量的值中自动推导出来。C# 3.0 中引入了隐式类型变量的概念。隐式类型变量并非旨在取代普通变量声明,它旨在处理一些特殊情况,如 LINQ(语言集成查询)。

例子:

// C# program to illustrate the concept
// of the implicitly typed variable
using System;

class geekdocsDemo {

    // Main method
    static public void Main()
    {

        // Creating and initializing
        // implicitly typed variables
        // Using var keyword
        var a = 'f';
        var b = "geekdocs geekdocs";
        var c = 30.67d;
        var d = false;
        var e = 54544;

        // Display the type
        Console.WriteLine("Type of 'a' is : {0} ", a.GetType());
        Console.WriteLine("Type of 'b' is : {0} ", b.GetType());
        Console.WriteLine("Type of 'c' is : {0} ", c.GetType());
        Console.WriteLine("Type of 'd' is : {0} ", d.GetType());
        Console.WriteLine("Type of 'e' is : {0} ", e.GetType());
    }
}

运行结果如下:

Type of 'a' is : System.Char 
Type of 'b' is : System.String 
Type of 'c' is : System.Double 
Type of 'd' is : System.Boolean 
Type of 'e' is : System.Int32

在 C# 4.0 中,引入了一种称为动态类型的新类型。它用于避免编译时类型检查。编译器不会在编译时检查动态类型变量的类型,而是编译器在运行时获取类型。动态类型变量是使用 dynamic 关键字创建的。

例子:

// C# program to illustrate how to get the
// actual type of the dynamic type variable
using System;

class geekdocsDemo {

    // Main Method
    static public void Main()
    {

        // Dynamic variables
        dynamic val1 = "geekdocs geekdocs";
        dynamic val2 = 3234;
        dynamic val3 = 32.55;
        dynamic val4 = true;

        // Get the actual type of
        // dynamic variables
        // Using GetType() method
        Console.WriteLine("Get the actual type of val1: {0}",val1.GetType().ToString());
        Console.WriteLine("Get the actual type of val2: {0}",val2.GetType().ToString());
        Console.WriteLine("Get the actual type of val3: {0}",val3.GetType().ToString());
        Console.WriteLine("Get the actual type of val4: {0}",val4.GetType().ToString());
    }
}

运行结果如下:

Get the actual type of val1: System.String
Get the actual type of val2: System.Int32
Get the actual type of val3: System.Double
Get the actual type of val4: System.Boolean

以下是 C# 中 var 和 dynamic 关键字之间的一些区别:

var dynamic
它是在 C# 3.0 中引入的 它是在 C# 4.0 中引入的
使用 var 关键字声明的变量是静态类型的 使用 dynamic 关键字声明的变量是动态类型的
变量的类型由编译器在编译时决定 变量的类型由编译器在运行时决定
这种类型的变量应该在声明时初始化。这样编译器就会根据它初始化的值来决定变量的类型。 这种类型的变量不需要在声明时初始化。因为编译器在编译时并不知道变量的类型。
如果变量未初始化,则会引发错误。 如果变量未初始化,则不会引发错误。
它支持 Visual Studio 中的智能感知。 它不支持 Visual Studio 中的智能感知
var myvalue = 10; // 语句1 myvalue = "geekdocs geekdocs"; // 语句2 这里编译器会抛出一个错误,因为编译器已经使用 语句1 确定了 myvalue 变量的类型,它是一个整数类型。当尝试将字符串分配给 myvalue 变量时,编译器将给出错误,因为它违反了安全规则类型。 dynamic myvalue = 10; // 语句1 myvalue = "geekdocs geekdocs"; // 语句2 在这里,尽管 myvalue 的类型是整数,但编译器不会抛出错误。当将字符串分配给 myvalue 时,它会重新创建 myvalue 的类型并接受字符串而不会出现任何错误。
它不能用于属性或函数的返回值,它只能用作函数中的局部变量。 它可用于属性或从函数返回值。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程