我正在开发WPF应用程序。
我正在尝试使用REF关键字通过引用传递对象,然后将其传递给构造函数中的另一个变量以稍后更改。但是,当我更改通过构造函数可变中参考的变量时,不会在范围外变化。
要解释,首先我创建变量并将其传递到另一个窗口的构造函数。
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
}
在这里,我将变量分配给初始定位,如果我尝试在此处更改它,则可以在外部变量上使用。
public partial class EditWindow : Window
{
public EditWindow(ref Location location, bool isEdit)
{
InitializeComponent();
InitialLocation = location;
//InitialLocation = ref location; //This is what I want my code to do
location.Name = "new"; //this changes varaiable outside scope
}
private Location InitialLocation;
在这里我更改初始定位,但更改不能在范围之外牢固。
private void ConfirmButton_Click(object sender, RoutedEventArgs e)
{
InitialLocation = new Location(CurrentLocation.Name, CurrentLocation.X, CurrentLocation.Y, InitialLocation.Update);
//But this doesn't change varaible outside scope
this.Close();
}
我想保留与Ref通过的对象,直到将其传递给的窗口被处置为止。可以在不等待封闭活动的情况下做吗?
我建议将初始定位声明为公共财产。
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;
}