构造函数 [closed] 中未赋值的 ref 值

Unassigned ref value in the constructor [closed]

提问人:Emre 提问时间:2/28/2022 更新时间:2/28/2022 访问量:80

问:


想改进这个问题吗?通过编辑这篇文章添加详细信息并澄清问题。

去年关闭。

我想在此代码中使用 ref 构造函数创建对象后,将 Data 类的输出值分配给 State 类。我该如何解决这个问题?

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# .NET 构造函数 Pass-by-Reference Ref

评论

0赞 stuartd 2/28/2022
究竟解决了什么问题?这会编译和运行吗?如果是这样,输出是什么?如果不是,错误是什么?
0赞 Emre 2/28/2022
我的目的是通过分配状态类对象来更改数据类值,但是 ref 值不能在构造函数上分配,所以这段代码无法运行,我不知道如何解决这个问题。
0赞 stuartd 2/28/2022
建议您阅读文档并查看那里的示例ref

答:

0赞 Federico Alterio 2/28/2022 #1

在 c# 中,ref 关键字与类似 C 的指针的概念相去甚远。这是您可以在该方向上执行的最接近的事情(使用安全代码):

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);
    }
}
0赞 Serge 2/28/2022 #2

你将不得不稍微纠正一下状态类

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