C# 3.0 feature 1--Implicitly typed local variables
我們來看下列變數宣告
var numbers=new int[]{1,2,3};
首先,C# compiler 會在同一個namespace範圍內尋找使用者自定義的var型別,如果找到,則把i, numbers做作var型別處理。如果沒找到,則認為i, numbers為implicitly typed local variables,並根據其初始值確實其型別,上述程式碼的IL程式碼和下列程式碼的IL相同
int[] numbers=new int[]{1,2,3};
使用Implicitly typed local variables時應遵守下列約束:
1. The declarator must include an initializer
2. The initializer must be an expression
3. The initializer expression must have a complie-time type which cannot be the null type.
4. The local variable declaration cannot include multiple declarations.
5. The initializer cannot refer to itself.
粗一看,額的神啊,一共有五條約束,還挺麻煩的,其實歸納下來主要就一句話,必須要讓編繹器能從initializer準確推斷出變數的型別,編繹器也是人啊,它需要根據推斷出來的型別為變數分配記憶體空間。
比如: var x = {1,2,3} //error, cannot infer the type from {1,2,3"}
var x = new int[]{1,2,"3}; // right. x is an array of type integer
最後說一下Implicitly typed local variable的使用範圍,它可不是到處能用。僅僅可以用於下面四種情況
1. 區域性變數宣告
2. for 語句中變數宣告)
3. using 語句初始化變數時.
4. foreach 中iterator型別宣告)
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-612013/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- C# 3.0 feature 2--Extension methodsC#
- Angular 18+ 高階教程 – Component 元件 の @let Template Local VariablesAngular元件
- QIBO CMS /inc/common.inc.php Local Variables Overriding Vul In $_FILESPHP
- C# 3.0新功能C#
- 效能優化篇 - css typed OM(css typed object model)優化CSSObject
- akka-typed(2) - typed-actor交流方式和交流協議協議
- Clouse Variables as Inputs
- [Bash] Environment variables
- [轉]Updating Session Variables from Dashboards using Presentation VariablesSession
- akka-typed(4) - EventSourcedBehavior in action
- CSS Typed Object Model, Async ClipbCSSObject
- Variables in Java 變數Java變數
- activiti變數variables變數
- SQL*Plus Substitution VariablesSQL
- akka-typed(3) - PersistentActor has EventSourcedBehavior
- MYSQL SHOW VARIABLES簡介MySql
- Type-Checking Variables
- proxysql global_variables 翻譯SQL
- Using Multiple Variables with the Same Name
- ORACLE程式之LOCAL=NO和LOCAL=YESOracle
- akka-typed(1) - actor生命週期管理
- variables_order引數詳解
- TensorFlow入門 - 變數(Variables)變數
- JavaScript30 - 3.CSS VariablesJavaScriptCSS
- MonoDevelop 3.0 大幅改進 C# 程式碼自動完成MonodevC#
- java new featureJava
- akka-typed(7) - cluster:sharding, 叢集分片
- akka-typed(8) - CQRS讀寫分離模式模式
- [譯] 開始使用新的 CSS Typed Object ModelCSSObject
- Asp.Net Core中Typed HttpClient高階用法ASP.NETHTTPclient
- C#與.NET入門之C# 8.0和.NET Core 3.0高階程式設計C#程式設計
- 17-Containers-Container Environment VariablesAI
- [轉]Updating Session Variables through GO URLSessionGo
- Selecting an Instance with Environment Variables (18)
- LOCAL_SHARED_LIBRARIES 與 LOCAL_LDLIBS,LOCAL_LDFLAGS的區別
- 7.89 FEATURE_DETAILSAI
- Feature homophily metric
- akka-typed(10) - event-sourcing, CQRS實戰