在 C# 中,当类的列表被修改时,如何更新类的字段?
我知道这里的东西是值类型并且没有被引用,所以当我更新列表时字段 _num 不会被修改。但我的问题是,当我修改包含它的列表时,如何更新字段 _num 被修改?
class Foo
{
public List<object> mylist;
private int _num;
public int num
{
get
{
return _num;
}
set
{
this._num = value;
mylist[0] = value;
}
}
public Foo()
{
mylist = new List<object>();
mylist.Add(_num);
}
}
class Program
{
static void Main(string[] args)
{
Foo my = new Foo();
my.num = 12;
my.mylist[0] = 5;
Console.WriteLine("" + my.mylist[0] + " " + my.num); ==> output is "5 12"
Console.ReadLine();
}
}
可以进行哪些更改以使列表和字段同步?就像我的输出应该是“5 5” 感谢您的帮助!
I understand things in here are value types and not referenced so the field _num won't be modified when I just update the list. But my question is how to update the field _num when I modify the list that contains it gets modified?
class Foo
{
public List<object> mylist;
private int _num;
public int num
{
get
{
return _num;
}
set
{
this._num = value;
mylist[0] = value;
}
}
public Foo()
{
mylist = new List<object>();
mylist.Add(_num);
}
}
class Program
{
static void Main(string[] args)
{
Foo my = new Foo();
my.num = 12;
my.mylist[0] = 5;
Console.WriteLine("" + my.mylist[0] + " " + my.num); ==> output is "5 12"
Console.ReadLine();
}
}
What changes could be done so the list and the field is synced? Like my output should be "5 5"
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是也可能不是您想要的......我仍然不确定是否需要按索引修改字段,但如果您真的想这样做,您是否考虑过适合您类型的索引器?也就是说,索引器将像这样替换您的列表:
然后您可以说:
This may or may not be what you want... and I'm still not sure I see the need for modifying the fields by index, but if you really want to do that have you considered an indexer for your type? That is, the indexer would replace your list like so:
Then you can either say: