隐式类型变量是在未显式指定.NET类型的情况下声明的那些变量。在隐式类型的变量中,编译器会在编译时从用于初始化变量的值中自动推导出变量的类型。隐式类型变量概念在C#3.0中引入。隐式类型变量并非旨在代替普通变量声明,而是为处理诸如LINQ(语言集成查询)之类的特殊情况而设计的。
问题:为什么将其称为“本地”?
答:不允许在方法中使用var作为参数值或返回类型,或者在类级别等上定义它,因为隐式类型变量的范围是local 。
例子:
// C# program to illustrate
// implicitly typed local variable
using System;
public class GFG {
// declaring and initializing implicitly
// typed local variable at class level.
// It will give compile time error
var imp = 15;
// Main method
static public void Main()
{
// trying to print the value of 'imp'
Console.WriteLine(GFG.imp);
}
}
编译时错误:
prog.cs(10,2): error CS0825: The contextual keyword `var’ may only appear within a local variable declaration
重要事项:
- 隐式类型变量通常使用var关键字声明,如下所示:
var ivariable = 10;
- 在隐式类型的变量中,不允许在单个语句中声明多个var ,如下所示:
var ivalue = 20, a = 30; // invalid
- 不允许在类级别使用var作为字段类型。
- 可以像下面这样在var中使用表达式:
Var b-=39
- 在C#中,没有任何初始化就无法声明隐式类型的变量,例如:
var ivalue; // invalid
- 不允许在隐式类型变量中使用null值,例如:
var value = null; // invalid
- 初始化程序不能包含任何对象或集合,它可以包含一个新表达式,该表达式包含一个对象或集合初始化器,例如:
// Not allowed var data = { 23, 24, 10}; // Allowed var data = new int [] {23, 34, 455, 65};
- 不允许使用不止一种类型的不同类型来初始化隐式类型的变量,例如:
// It will give error because // the type of the value is different // one is of string type and another // one is of int type var value = "sd" value = new int[]{1, 2, };
范例1:
// C# program to illustrate the
// concept of implicitly typed variable
using System;
public class GFG {
// Main method
static public void Main()
{
// Declaring and initializing
// implicitly typed variables
var a = 50;
var b = "Welcome! Geeks";
var c = 340.67d;
var d = false;
// Display the type of the variables
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());
}
}
输出:
Type of 'a' is : System.Int32
Type of 'b' is : System.String
Type of 'c' is : System.Double
Type of 'd' is : System.Boolean
范例2:
// C# program to illustrate the
// use of implicitly typed variable
using System;
class GFG {
// Main method
static public void Main()
{
// implicitly typed variables
var Base = 13;
var Height = 20;
var Area = (Base * Height) / 2;
// Display result
Console.WriteLine("Height of triangle is: " + Height
+ "\nBase of the triangle is: " + Base);
Console.Write("Area of the triangle is: {0}", Area);
}
}
输出:
Height of triangle is: 20
Base of the triangle is: 13
Area of the triangle is: 130
注意:隐式类型的局部变量可以在函数,foreach和for循环中用作局部变量,在LINQ查询表达式中,在using语句中用作匿名类型。