📜  C#中的var关键字

📅  最后修改于: 2021-05-29 15:53:49             🧑  作者: Mango

关键字是用于某些内部过程或表示某些预定义动作的语言中的单词。 var是关键字,用于声明隐式类型变量,该变量根据初始值指定变量的类型。

句法:

var variable_name = value;

例子:

Input: a = 637
       b = -9721087085262

Output: value of a 637, type System.Int32
        value of b -9721087085262, type System.Int64

Input: c = 120.23f
       d = 150.23m
       e = G
       f = Geeks
Output: value of c 120.23, type System.Single
        value of d 150.23, type System.Decimal
        value of e G, type System.Char
        value of f Geeks, type System.String

范例1:

// C# program for var keyword
using System;
using System.Text;
  
class GFG {
  
    static void Main(string[] args)
    {
  
        var a = 637;
        var b = -9721087085262;
  
        // to print their type of variables
        Console.WriteLine("value of a {0}, type {1}", a, a.GetType());
        Console.WriteLine("value of b {0}, type {1}", b, b.GetType());
    }
}

输出:

value of a 637, type System.Int32
value of b -9721087085262, type System.Int64

范例2:

// C# program for var keyword
using System;
using System.Text;
  
namespace Test {
  
class GFG {
  
    static void Main(string[] args)
    {
  
        var c = 120.23f;
        var d = 150.23m;
        var e = 'G';
        var f = "Geeks";
  
        // to print their type of variables
        Console.WriteLine("value of c {0}, type {1}", c, c.GetType());
        Console.WriteLine("value of d {0}, type {1}", d, d.GetType());
        Console.WriteLine("value of e {0}, type {1}", e, e.GetType());
        Console.WriteLine("value of f {0}, type {1}", f, f.GetType());
  
        // hit ENTER to exit
        Console.ReadLine();
    }
}
}

输出:

value of c 120.23, type System.Single
value of d 150.23, type System.Decimal
value of e G, type System.Char
value of f Geeks, type System.String