将ref关键字扩展到另一个变量

时间:2017-12-02 14:25:58

标签: c# wpf

我正在开发wpf应用程序。

我正在尝试使用ref关键字通过引用传递对象,然后将其传递给构造函数中的另一个变量以稍后更改它。但是当我更改我传递的变量时,构造函数中的引用变量不会改变外部范围。

为了解释,首先我创建变量并将其传递给另一个窗口的构造函数。

variable

这里我将变量赋给InitialLocation,如果我尝试在此处更改它,则它适用于外部变量。

tf.Variable

这里我更改了InitialLocation,但更改不会超出范围。

private void LocatonEditButton_Click(object sender, RoutedEventArgs e)
    {
        var location = new Location(SelectedLocation.Name, SelectedLocation.X, SelectedLocation.Y, SelectedLocation.Update); 
        //Creating object
        var result =  new EditWindow(ref location,true).ShowDialog();
        //And passing it to another window with ref
    }

我希望保留通过ref传递的对象,直到我传递给它的窗口被处理掉。 是否可以不等待已结束的活动?

1 个答案:

答案 0 :(得分:1)

我建议将InitialLocation声明为公共属性。

public partial class EditWindow : Window
{
    public EditWindow(Location location, bool isEdit)
    {
        InitializeComponent();
        InitialLocation = location;
        location.Name = "new";
    }

    public Location InitialLocation { get; set; }

    private void ConfirmButton_Click(object sender, RoutedEventArgs e)
    {
        InitialLocation = new Location(CurrentLocation.Name, CurrentLocation.X, CurrentLocation.Y, InitialLocation.Update);
        this.Close();
    }
}

编辑后读取该属性的值:

private void LocatonEditButton_Click(object sender, RoutedEventArgs e)
{
    var location = new Location(SelectedLocation.Name, SelectedLocation.X, SelectedLocation.Y, SelectedLocation.Update); 

    var editWindow = new EditWindow(location, true);
    var result = editWindow.ShowDialog();

    var changedLocation = editWindow.InitialLocation;
}