构造函数中未分配的引用值

Unassigned ref value in the constructor

在这段代码中,我想在使用引用构造函数创建对象到状态 class 后,将数据 class 的输出值分配给状态 class。我该如何解决?

class Program
{
    static void Main(string[] args)
    {
        Data data = new Data();
        State stateA = new State("A", ref data.outputA);
        State stateB = new State("B", ref data.outputB);
        stateA.output = 10;
        stateB.output = 8;
        Console.WriteLine(data.outputA); //10
        Console.WriteLine(data.outputB); //8
        Console.ReadLine();
    }
}
public class Data
{
    public int outputA;
    public int outputB;
}
public class State
{
    public string name;
    public ref int address;
        
    public State(string _name, ref int _output)
    {
        this.name = _name;
        address = _output;
    }
}

在 c# 中,ref 关键字与 C-like 指针的概念相去甚远。这是您可以朝那个方向做的最接近的事情(使用安全代码):

class Program
{
     static void Main(string[] args)
    {
        Data data = new Data();
        State stateA = new State("A", value => data.outputA = value, () => data.outputA);
        State stateB = new State("B", value => data.outputB = value, () => data.outputB);
        stateA.Output = 10;
        stateB.Output = 8;
        Console.WriteLine(data.outputA); //10
        Console.WriteLine(data.outputB); //8
        Console.ReadLine();
    }
}


public class Data
{
    public int outputA;
    public int outputB;
}
public class State
{
    public string name;
    private Action<int> _outputSetter;
    private Func<int> _outputGetter;

    public State(string _name, Action<int> _outputSetter, Func<int> _outputGetter)
    {
        this.name = _name;
        this._outputSetter = _outputSetter;
        this._outputGetter = _outputGetter;
    }


    public int Output
    {
        get => _outputGetter();
        set => _outputSetter(value);
    }
}

你需要更正状态 class 一点

  Data data = new Data();
    State stateA = new State("A", ref data);
    State stateB = new State("B", ref data);
    stateA.output = 10;
    stateB.output = 8;
    Console.WriteLine(data.outputA); //10
    Console.WriteLine(data.outputB); //8
    Console.ReadLine();

public class State
{
    public int output
    {
        get { return name == "A" ? address.outputA : address.outputB; }
        set { if(name == "A") address.outputA = value; else   address.outputB = value; }
    }

    public string name;
    public Data address;

    public State(string _name, ref Data _output)
    {
        this.name = _name;
        address = _output;
    }
}