2015-09-29 31 views
5

String.Empty""と同程度の場合、コンパイラはどのようにcase文でstring.Emptyをスローしますか?私の見解では、string.Emptyよりも一定のものはありません。誰でも知っていますか?ありがとう!あなたが代わりにこのようにしてみてくださいSwitch/case文のString.Emptyはコンパイルエラーを生成します

switch (filter) 
      { 
    case string.Empty: // Compiler error "A constant value is expected" 

       break; 

       case "": // It's Okay. 
        break; 

      } 
+0

はこちらをご覧くださいその場合にのみ値を読み取ることができますスイッチ:http://stackoverflow.com/questions/2701314/cannot-use-string-empty-as-a-defaultを-value-for-an-optional-parameter – blfuentes

+0

@blacaiありがとう!それは良い読書でした! – Zuzlx

答えて

6

""は、コンパイル時定数であるのに対し、

switch(filter ?? String.Empty) 

string.Emptyは読み取り専用フィールドです。また、サイドノートではコードプロジェクトString.Empty Internals

//The Empty constant holds the empty string value. 
//We need to call the String constructor so that the compiler doesn't 
//mark this as a literal. 
//Marking this as a literal would mean that it doesn't show up as a field 
//which we can access from native. 

public static readonly String Empty = ""; 

にここに記事を行くことができます:あなたはあなたのメソッド内でデフォルトのパラメータ値を提供しているときにも、この問題が表示されます

(C#4.0 ):

void myMethod(string filter = string.Empty){} 

デフォルト値は定数である必要があるため、上記の結果はコンパイル時エラーになります。

+0

ありがとうラフル。しかし、私はstring.Emptyをどうやって使うことができないのか不思議に思っていました。それは私にとっては奇妙なことです。 – Zuzlx

+0

@Zuzlx: - 私が知る限り、 'string.Empty'は読み取り専用フィールドですが、' '"はコンパイル時定数です。 –

+0

意味があります。再度、感謝します。私たちは火星に水があることを知ることができますが、悲しいことに "string.Empty'テストを使うことはできません。 – Zuzlx

3

理由

あなたがた場合のreadonly値を使用することはできません。次のシナリオを検討してください。

public string MyProperty { get; } // is a read only property of my class 
    switch (filter) 
    { 
     case MyProperty: // wont compile this since it is read only 
     break; 
      // rest of statements in Switch 
    } 

あなたはstring.Empty""と等価です言ったように、ここで私は、switch文の同じ例でこれを証明することができます。

string filter = string.Empty; 
switch (filter) 
    { 
     case "": // It's Okay. 
     break; 
     //rest of statements in Switch 
    } 

そして、文句を言わない許可のための唯一の理由の場合はstring.Emptyです。それは読み取り専用 で、文句を言わない

関連する問題