2017-10-26 14 views
2

アレイプロパティCoolerFanIsOnのゲッターとセッター式をクラスCoolerSystemに書き込むにはどうすればよいですか?非配列プロパティIsOnLampクラスの同様の望ましい式を示しました。C#:配列プロパティのゲッターとセッター式

class CoolerFan{ 

    bool isOn; 
    public bool IsOn { 
     get => isOn; 
     set { 
      isOn = value; 
     } 
    } 
} 

class CoolerSystem { 

    private CoolerFan[] = new CoolerFan[5]; 
    private bool[] coolerFanIsOn = new Boolean[5]; 

    // invalid code from now 

    public bool[] CoolerFanIsOn { 
     get => coolerFanIsOn[number]; 
     set { 
      coolerFanIsOn[number] = value; 
     } 
    } 
} 
+0

あなたの欲望を明確にしてください。 –

+2

[indexer](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/)を実装しようとしていますか? –

+0

どうしてクラスに2つの配列がありますか? IMHO、 'IsOn'は' CoolerFan'クラスのプロパティでなければなりません。 –

答えて

5

あなたはindexerを使用することができます。

public class CoolerSystem 
{ 
    private bool[] _coolerFanIsOn = new Boolean[5]; 

    public bool this[int index] 
    { 
     get => _coolerFanIsOn[index]; 
     set => _coolerFanIsOn[index] = value; 
    } 
} 

ところで、=>はC#6の新ましたexpression bodied propertiesです。あなたが使用できない場合は、古い構文を使用します(セッターは、C#で新しいだった7)、インデクサは、それとは何の関係(C#3)を持っていない:

public bool this[int index] 
{ 
    get { return _coolerFanIsOn[index]; } 
    set { _coolerFanIsOn[index] = value; } 
} 
+0

私はこれがC#7ではサポートされていて、C#6ではサポートされていないと思います。 – Transcendent

+1

C#6のエクスプレッションボディのプロパティは、ゲッター(C#7で起動されたセッター)にのみ適用されます。 –

+0

@ TetsuyaYamamoto: 'String x =>" x ";またはString x {get;} = "x" 'はC#6でサポートされています。私はC#6コンパイラでチェックしただけで、 'String x {get =>" x ";}'は '{} 'が期待されているとコンパイルしませんでした。 – Transcendent

0

は多分これはあなたがやりたいものです。

class CoolerSystem 
{ 

    private CoolerFan[] _fans = new CoolerFan[5]; 

    private bool[] _coolerfanIsOn; 

    public bool[] CoolerFanIsOn 
    { 
     get { return _coolerfanIsOn; } 
     set 
     { 
      _coolerfanIsOn = value; 
     } 
    } 

    public bool GetFanState(int number) 
    { 
     return CoolerFanIsOn[number]; 
    } 

    public void SetFanState(int number, bool value) 
    { 
     CoolerFanIsOn[number] = value; 
    } 
} 
2

あなたはあなたのクラス

のインデクサを書くことができます
public bool this[int index]{ 
    get { return coolerFanIsOn[index]; } 
    set { coolerFanIsOn[index] = value;} 
} 
関連する問題