Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9749

C# 6.0 の記述方法

$
0
0

C# 6.0 の新機能

読み取り専用の自動プロパティ (Read-only auto-properties)

自動実装プロパティで読み取り専用を記述できるようになった。

classPerson{publicDateTimeBirth{get;}=newDateTime(1999,12,31);}

以前の書き方

フィールドを用意する必要があった。
classPerson{privateDateTimebirth=newDateTime(1999,12,31);publicDateTimeBirth{get{returnthis.birth;}}}

自動プロパティ初期化子 (Auto-property initializers)

自動実装プロパティの初期値を指定できるようになった。

classPerson{publicDateTimeBirth{get;set;}=newDateTime(1999,12,31);}

以前の書き方

コンストラクタで初期化する必要があった。
classPerson{publicPerson(){this.Birth=newDateTime(1999,12,31);}publicDateTimeBirth{get;set;}}

ラムダ式によるメソッドとプロパティ (Expression-bodied function members)

メソッド (Methods)

簡単なメソッドを1行で書けるようになった。

classPerson{privateDateTimebirth=newDateTime(1999,12,31);publicintGetAge()=>DateTime.Today.Year-this.birth.Year+1;// 数え年}

以前の書き方

1行で書けなかった。
classPerson{privateDateTimebirth=newDateTime(1999,12,31);publicintGetAge(){returnDateTime.Today.Year-this.birth.Year+1;// 数え年}}

using static

static クラスのメソッド呼び出し等に、クラス名が省略可能になった。

usingstaticSystem.Math;staticclassUtil{publicstaticintRange(intvalue,intlower,intupper){returnMax(Min(value,lower),upper);}}

Null 条件演算子 (Null-conditional operators)

イベント発生等を簡潔に書けるようになった。

classPerson{privatestringname;publicstringName{get{returnthis.name;}set{this.name=value;this.NameChanged?.Invoke(this,EventArgs.Empty);}}publiceventEventHandlerNameChanged;}

以前の書き方

null チェックの必要があった。
classPerson{privatestringname;publicstringName{get{returnthis.name;}set{this.name=value;varhandler=this.NameChanged;if(handler!=null)handler(this,EventArgs.Empty);}}publiceventEventHandlerNameChanged;}

文字列補間 (String interpolation)

文字列の書式化が簡単になった。

varmessage=$"ファイル {path}が存在しません。";

以前の書き方

string.Format を使う必要があった。
varmessage=string.Format("ファイル {0} が存在しません。",path);

例外フィルター (Exception filters)

nameof 式 (The nameof expression)

変数などの名前を文字列として取得できるようになった。

if(path==null)thrownewArgumentNullException(nameof(path));

以前の書き方

文字列で指定する必要があったため、リファクターの対象にならなかった。
if(path==null)thrownewArgumentNullException("path");

Catch ブロックと Finally ブロックでの Await (Await in Catch and Finally blocks)

インデクサーを使用して関連コレクションを初期化する (Initialize associative collections using indexers)


Viewing all articles
Browse latest Browse all 9749

Trending Articles