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.ReadL开发者_如何学Pythonine();
}
}
What changes could be done so the list and the field is synced? Like my output should be "5 5" Thanks for the help!
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:
class Foo
{
public int num;
public string name;
public bool isIt;
public object this[int index]
{
get
{
switch(index)
{
case 0:
return num;
case 1:
return name;
case 2:
return isIt;
default:
throw new ArgumentOutOfRangeException();
}
}
set
{
switch(index)
{
case 0:
num = (int) value;
break;
case 1:
name = (string) value;
break;
case 2:
isIt = (bool) value;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
Then you can either say:
var foo = new Foo();
foo.num = 13; // either works
foo[0] = 13; // either works
精彩评论