我有看起来像这样的代码;
public ObservableCollection<ParamViewModel> ListOfPhrases{
get => _listOfPhrases;
set => SetProperty(ref _listOfPhrases, value);
}
public class ParamViewModel : ObservableObject
{
bool _selected;
int _id;
string _name;
string _state;
public bool Selected { get => _selected; set => SetProperty(ref _selected, value); }
public int Id { get => _id; set => SetProperty(ref _id, value); }
public string Name { get => _name; set => SetProperty(ref _name, value); }
public string State { get => _state; set => SetProperty(ref _state, value); }
}
private void OnPhraseTapped(string btnText)
{
ListOfPhrases.ForEach(x => x.Selected = false);
var first = ListOfPhrases.FirstOrDefault(x => x.Name == btnText);
if (first != null) first.Selected = true;
因此,当btnText为ABC时,它将首先使用ListOfPhrases列表的元素进行填充。然后将first的值设置为true。
我的问题是。为什么更改first的Selected值会更改ListOfPhrases中的条目?
If I create this code:
var a = "ABC";
var b = a;
b = "x"
那我相信改变b
不会改变价值a
参考文献。
长话短说; 对象由REFERENCE分配。而值类型是自我包含在它们自己的内存空间中的。
例:
// assume the constructor argument assigns to the public property Value
var listOfObjects = new List<SomeObject>() {
new SomeObject(1),
new SomeObject(2)
}
var a = listOfObjects[0];
var a.Value = 3;
// will print out 3 instead of 1
Console.WriteLine(listOfObjects[0].Value);
您将希望对此有所了解。这是在面向对象编程和C#中要理解的一个非常重要的概念。
为了理解这一点,我强烈建议阅读以下内容:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句