C# 3.0 中隐式变量的基本理解






3.19/5 (12投票s)
本文将简要介绍 .net Framework 3.0 及更高版本提供的隐式变量,并说明其用法。
引言
从 Visual C# 3.0 开始,在方法作用域中声明的变量可以使用隐式类型 var。 隐式类型的局部变量就像您自己声明类型一样,具有强类型,但编译器会确定类型。我想将上述内容总结如下:var 关键字是一种允许编译器为您推断类型的简写方式 - 可以节省您的一些手指工作。
背景
C# 3.0 现在为我们提供了一个名为 var 的新关键字,可以用它来代替指定正式数据类型(例如 int、float、string 或 bool)。 当我们使用 var 关键字时,编译器将自动从初始化语句右侧的表达式推断变量的类型。 推断的类型可以是内置类型、匿名类型、用户定义的类型或在 .NET Framework 类库中定义的类型。
需要明确一些事项
- 使用 var 并不会使您的变量“弱类型”。 声明为 var 的所有变量都是强类型的。
- var 不是一种类型。 实际类型是在编译时确定的。
- 由于实际类型是在编译时解析的,因此 var 关键字不会“变慢”。
使用代码
var 关键字的基本理解
假设有一个方法说明了如何声明显式变量。
void DeclaringExplicitVariables() { // datatype variablename = intialvalue; int testInt = 0; float testFloat = 0.0f; string testString = “writing code”; bool testBool = false; }
现在我们将以变量声明为隐式变量的方式重写上述方法。
void DeclaringImplicitVariables() { // var variablename = intialvalue; var testInt = 0; var testFloat = 0.0f; var testString = "writing code"; var testBool = false; }
我们还可以使用反射确定隐式变量在初始化后分配的变量类型,如下所示:
void GetTypeofImplicitVariables() { var testInt = 0; var testFloat = 0.0f; var testString = "writing code"; var testBool = false; var wholeNumbers = new int[] {0,1,2,3}; var testStringList = new List<String>(); Console.WriteLine("type of testInt is : {0}", testInt.GetType().Name); Console.WriteLine("type of testFloat is : {0}", testFloat.GetType().Name); Console.WriteLine("type of testString is : {0}", testString.GetType().Name); Console.WriteLine("type of testBool is : {0}", testBool.GetType().Name); Console.WriteLine("type of wholeNumbers is : {0}", wholeNumbers.GetType().Name); Console.WriteLine("type of testStringList is : {0}", testStringList.GetType().Name); Console.ReadLine(); }
上述程序的输出将是:
type of testInt is : Int32 type of testFloat is : Single type of testString is : String type of testBool is : Boolean type of wholeNumbers is : Int32[] type of testStringList is : List’1
var 变量可以用于通过 foreach 循环进行循环。 顾名思义,编译器会自动推断出正确的类型。
void VarUsageInForEachLoop() { var wholeNumbers = new int[] {0,1,2,3}; foreach(var item in wholeNumbers) { Console.WriteLine("Item value : {0}", item); } }
使用隐式变量的注意事项
1. 它只能用作方法或属性作用域中的局部变量。 在字段类型、返回值或参数中使用它们是非法的。
class ErrorClass { //Error as implicit variables can’t be used as field type private var testInt = 0; // Error as var can neither be used as parameter nor as return type public var ErrorMethod(var first, var second) { var sum = fisrt+second; return sum; } }
2. 隐式变量必须在声明时分配初始值,并且不能分配为 null。
//Error as it must be assigned a value var testInt; //Error as value must be assigned at exact time of declaration var testInt; testing = 0; //Error as it can’t be initialize to null var testObj = null;
3. 完全可以向引用类型隐式变量分配 null 值,只要在初始化后。
// It’s correct only if LivingBeing is reference type var humanBeing = new LivingBeing(); humanBeing = null;
4. 完全可以将隐式类型局部变量的值分配给其他变量的值。
var testInt = 0; var secondInt = testInt; float testFloat = 0.0f; var secondFloat = testFloat;
5. 隐式变量可用于在方法返回类型与定义的 var 变量类型相同的情况下,将值发送到调用方法。
string ReturnString() { var retVariable = "hello world"; return retVariable; }
6. 不允许直接声明可为空的隐式变量类型。
//Error as implicit variables can’t be of nullable type var? testInt = 0; var? testFloat = 0.0f;
7. 在声明隐式类型数组时,应记住它们是相同类型(即全部为 int,或全部为 string,但不能混合使用)。
//Correct as all data are of integer type. var intArray = new[] {2,5,8,12}; //Error as data are of mixed type var mixArray = new[]{1, “hello”, 2, “world”};
关注点
我希望阅读本文后,您对 C# 中的 var 变量有更清晰的认识,并且可以经常在日常代码中使用它。
祝大家阅读本文愉快,就像我写这篇文章一样。