2013-01-10 27 views
1

我一直在研究一些電氣網絡仿真軟件(ElecNetKit)。在電氣網絡中,有時使用單相模型有時很方便,有時使用三相模型。在一個班級成員中表示多個值

因此,我想是能夠代表電網元件之一:

class Bus 
{ 
    public Complex Voltage {set; get;} //single phase property 
} 

但同時以一種方式,使得用戶可以調用Bus.Voltage.Phases[x],並期望一個Complex對於任何有效整數x

Bus.Voltage屬性應該映射到Bus.Voltage.Phases[1]當作爲Complex對待。

我有兩個問題在這裏:

  1. 這是違反任何OOP原則是什麼?我有一種感覺,它可能是。
  2. 有沒有一種方便的方式來表示這在C#中?

在代表性方面,我嘗試過:

  • Phased<T> : T,但這是與打字系統不兼容,並
  • Phased<T>與通用轉換器輸入T ,但轉換器仍然需要調用。

我知道,我可以簡單地使用類似:

public Dictionary<int,Complex> VoltagePhases {private set; get;} 
public Complex Voltage { 
    set {VoltagePhases[1] = value;} 
    get {return VoltagePhases[1];} 
} 

,但有很多重複的,一旦你開始爲多個屬性做到這一點,在多個類別。

回答

1

我會提出這樣的:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Diagnostics; 
using System.Numerics; 

namespace Test 
{ 
    class PhaseList 
    { 
     private Dictionary<int, Complex> mPhases = new Dictionary<int, Complex>(); 

     public Complex this[int pIndex] 
     { 
      get 
      { 
       Complex lRet; 
       mPhases.TryGetValue(pIndex, out lRet); 
       return lRet; 
      } 
      set 
      { 
       mPhases.Remove(pIndex); 
       mPhases.Add(pIndex, value); 
      } 
     } 
    } 

    class PhasedType 
    { 
     private PhaseList mPhases = new PhaseList(); 
     public PhaseList Phases { get { return mPhases; } } 
     public static implicit operator Complex(PhasedType pSelf) 
     { 
      return pSelf.Phases[1]; 
     } 

     public static implicit operator PhasedType(Complex pValue) 
     { 
      PhasedType lRet = new PhasedType(); 
      lRet.Phases[1] = pValue; 
      return lRet; 
     } 
    } 

    class Bus 
    { 
     public PhasedType Voltage { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      Bus lBus = new Bus(); 

      lBus.Voltage = new Complex(1.0, 1.0); 
      Complex c = lBus.Voltage; 
      lBus.Voltage.Phases[1] = c; 
      c = lBus.Voltage.Phases[1]; 
     } 
    } 
} 
+0

只是要小心隱含的運營商,他們一般是,即使他們可能使你的代碼看起來有點簡單,一個壞主意。 – lahsrah

1

你能做這樣的事嗎?這將起到類似於底層解決方案的作用,但由於泛型類,您不會重複每個屬性的代碼。

class Program 
{ 
    static void Main(string[] args) 
    { 
     Collection<Complex> complex = new Collection<Complex>(); 
     //TODO: Populate the collection with data 

     Complex first = complex.First; 
     Complex another = complex.Items[2]; 
    } 
} 

public class Complex 
{ 
    // implementation 
} 


public class Collection<T> where T : class 
{ 
    public List<T> Items { get; set; } 

    public T First 
    { 
     get 
     { 
      return (Items.Count > 0) ? Items[1] : null; 
     } 
     set 
     { 
      if(Items.Count > 0) 
       Items[1] = value; 
     } 
    } 
} 
相關問題