2017-04-28 12 views
0

ユーザーがこのフィールドを埋めるのではない場合は「理由を明示しません」と表示したい場合や、ユーザーが入力した場合はユーザー入力を表示します。 このコードでは、理由を理解できませんが、フィールドを埋める場合でも、「説明されていない理由」が表示されます。nullまたは空の文字列を確認してください

private string reason; 
    public string Reason 
    { 
     get 
     { 
      return this.reason; 
     } 
     set 
     { 
      if (string.IsNullOrEmpty(this.Reason)) 
       this.reason = "reason not explicited"; 
      else this.reason = value; 
     } 
    } 

    [Pure] 
    public static bool IsNullOrEmpty(String value) { 
     return (value == null || value.Length == 0); 
    } 
+2

'(string.IsNullOrEmpty場合を(値))this.reason = "理由を明示しない" ...; –

+2

適切な検証メッセージを表示する代わりに、基本的なクライアント側の検証を使用します。 mvc検証を使用している場合は、プロパティ属性を使用することもできます。これをモデルロジックにハードコードしないでください。 – Igor

答えて

6

あなたがプロパティの代わりの値をチェックしているので、単に正しい動作を処理するために、あなたのセッターに

set 
{ 
    if (string.IsNullOrEmpty(value)) 
     this.reason = "reason not explicited"; 
    else 
     this.reason = value; 
} 
3

valueを使用しています。
現在のコードは、プロパティがnullまたは空の場合にのみプロパティの値を設定します。
それは

set 
    { 
     if (string.IsNullOrEmpty(value)) 
      this.reason = "reason not explicited"; 
     else this.reason = value; 
    } 

、あるいは良いはずです:

set 
    { 
     this.reason = (string.IsNullOrEmpty(value)) ? "reason not explicited": value; 
    } 
0

はあなたが変更されたときに

if (string.IsNullOrEmpty(value)) 
       this.reason = "reason not explicited"; 
      else this.reason = value; 
0

セッターは(トリガする機能IsNullOrEmpty関数にを渡す必要があります値を割り当てる)ので、ユーザーがそのフィールドをスキップすると、設定者はトリガーしません。しかし、プロパティの値にアクセスすると、ゲッターがトリガーされます。だからあなたのケースでは、理由がnullまたは空の場合は、"reason not explicited"と表示されます取得の中にロジックを適用する場合。だから、新しいロジックは次のように次のようになります。

get 
{ 
    if (string.IsNullOrEmpty(this.reason)) 
     return "reason not explicited"; 
    else this.reason = value; 
     return this.reason; 
} 
set 
{ 
    this.reason = value; 
} 

別の解決策は次のようになります。

ユーザーがフィールドをスキップしてもそう"reason not explicited"とバックアッププロパティを初期化(セッターがトリガされません)お印刷されるデフォルト値を取得します。そして、あなたは、それはゲッターだ呼び出し、問題はコード

このプロパティの値を取得しようとしている
if (string.IsNullOrEmpty(this.Reason)) 

のこの行であるvalue

private string reason = "reason not explicited"; 

public string Reason 
{ 
    get { return this.reason; } 
    set 
    { 
     if (String.IsNullOrEmpty(value)) 
      this.reason = "reason not explicited"; 
     else 
      this.reason = value; 
    } 
} 
+0

ゲッターは値を変更すべきではありません。 – Aphelion

+0

誤った解決策。 –

+0

私はそれをお勧めしません。ゲッターは実際の値を返します。 – ATC

1

に基づいてバックアッププロパティを更新する必要がありますreasonフィールドの値を返します。そして、このフィールドは、あなたが価値を得ようとしている瞬間に正しい値で埋められません。

具体的な入力値のnullまたは空の文字列のであれば、あなたがチェックするようにコードを変更する必要があります:あなたはthis.Reasonvalueをしませチェックする必要があり

if (string.IsNullOrEmpty(value)) 
3

public string Reason 
    { 
     get 
     { 
      return this.reason; 
     } 
     set 
     { 
      this.reason = string.IsNullOrEmpty(value) 
       ? "reason not explicited" 
       : value; 
     } 
    } 
関連する問題