Variable Reference to Other Variable

Viewed 65

I have two class.

One has data about class, other send to data when serial communication.

Example

class Data
{
    public int Voltage = 10;
}


class ForCommunication
{
    public object values;
}
...

// Main Form
Data Data = new Data();
private void SetValue
{
    ForCommunication fc = new ForCommunication();
    fc.values = Data.Voltage;
}

And even if fc.values were changed by serial communications, the Data.Voltage does not change.

I want change Data.Voltage when fc.values change.

Example

// init values
Data.Voltage = 10;
fc.values = Data.Voltage;
fc.values = 10;
// Data.Voltage : 10, fc.values : 10

// fc.values change
fc.values = 15;
// and I want Data.Voltage change
// fc.values : 15, Data.Voltage : 15

Is It possible on C#?

Should I find another way?

1 Answers

It seems like a design problem. I don't provide a direct answer but a solution easier to maintain in the future.

Please edit if my suggestion doesn't match your use case.

There are 2 roles (classes) in your use case.

  1. A serial communication keeps receiving data.
  2. I assume you have a pure data ( model ) for view.

My suggestion is let serial communication trigger a change event while data received.

A SerialComm with delegate for notifying data received.

    public class SerialComm
    {
        delegate void DataReceived( int value );
        public DataReceived NotifyDataReceived;

        void polling()
        {
            // ...
            int data = 0;
            // Found data
            data = somevalue;
            NotifyDataReceived?.Invoke( data );
            // ...
        }
    }

At mainform, update your data when SerialComm.NotifyDataReceived fired.

    // mainform
    class Data
    {
        public int Value;
    }
    Data m_Data = new Data();
    SerialComm m_Comm;

    void Init()
    {
        m_Comm = new SerialComm();
        m_Comm.NotifyDataReceived += OnDataReceived;
    }

    void OnDataReceived( int value )
    {
        m_Data.Value = value;
    }
Related