表示一个类成员中的多个值

本文关键字:成员 一个 表示 | 更新日期: 2023-09-27 17:51:13

我一直在研究一些电气网络仿真软件(ElecNetKit)。在电网中,有时使用单相模型很方便,有时使用三相模型。

因此,我希望能够将其中一个电子网络元素表示为:

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

,但同时以一种方式,这样用户可以调用Bus.Voltage.Phases[x],并期望Complex对于任何有效的整数x

当作为Complex处理时,Bus.Voltage属性应该映射到Bus.Voltage.Phases[1]

我有两个问题:

  1. 这是否违反了任何面向对象原则?我有一种感觉它可能是。
  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];}
}

但是一旦你开始在多个属性,多个类中这样做就会有很多重复

表示一个类成员中的多个值

我的建议是:

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];
        }
    }
}

你能这样做吗?这将类似于您在底部的解决方案,但由于泛型类,您不需要重复每个属性的代码。

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;
        }
    }
}