2016-11-09 11 views
1

私は一つのクラスがあります:プロパティColorまたはSpeedは私がの連結でProperty3の値を設定したい更新自動的にプロパティ

を更新しているとき、私は自動的にProperty3の値を設定したい

public class Car 
{ 
    public string Color { get; set; } 

     public string Speed { get; set; } 

     public string Property3 { get; set; } 
} 

を値ColorSpeedはハイフンで区切ります

これを行うにはどのような方法が最適ですか?

答えて

2

あなたはProperty3のゲッターであることを指定することができます - このような何か:

public string Property3 
{ 
    get { return $"{this.Color}-{this.Speed}"; } 
} 

私はあなたがProperty3だけので、私はあなたが持っている

+1

のようなものゲッタープロパティを設定することができます – Izzy

0

上記のサンプルでセッターを省略読み取ることがしたいことを想定し二つの方法:

更新速度や色のセッター内の依存プロパティ:

private string _Color; 
public string Color 
{ 
    get 
    { 
     return this._Color; 
    } 
    set 
    { 
     this._Color = value; 
     this.Property3 = $"{this.Color}-{this.Speed}"; 
    } 
} 

private string _Speed; 
public string Speed 
{ 
    get 
    { 
     return this._Speed; 
    } 
    set 
    { 
     this._Speed = value; 
     this.Property3 = $"{this.Color}-{this.Speed}"; 
    } 
} 
public string Property3 { get; set; } 
依存プロパティの取得中

連結:

public string Property3 
{ 
    get 
    { 
     return $"{this.Color}-{this.Speed}"; 
    } 
} 

概念差は非常に明白です:あなたはProperty3を上書きすることができるようにしたいか、それが読み取り専用にする必要がありますか。

1

あなたはOPのスニペットは、C#6.0の構文を使用していることを知っているしたい場合があります。この

public string Property3 { 
    get { return Color + "-" + Speed; } 
} 
関連する問題