class Foo
{
public List<object> mylist;
public int num;
public string name;
public bool isIt;
public Foo()
{
mylist = new List<object>();
mylist.Add(num);
mylist.Add(name);
mylist.Add(isIt);
}
}
class P开发者_StackOverflow中文版rogram
{
static void Main(string[] args)
{
Foo my = new Foo();
my.isIt = true;
my.mylist[0] = 5;
my.mylist[1] = "Hello";
Console.WriteLine("" + my.mylist[2]); => returns false instead of true
Console.ReadLine();
}
}
The reason your code is not returning true is because your list is holding different references than the fields when you change the value using the field instead of the list.
In your constructor when you call:
mylist.Add(isIt);
It adds the value false
boxed in an object
.
Then in your Main
, when you do:
my.isIt = true;
You are modifying the field, but the list still refers to the boxed object you added in the constructor. If you want to change the value stored in the list, you have to reference the list like you did originally:
my.myList[2] = true;
But this will not link the fields to the list, because they refer to different copies of the data (in the case of the string, different copies of a reference to an immutable type). You can change what one points to, but it won't automatically change what the other points to.
The same thing would be true if you tried to set any of the other fields:
my.isIt = true;
my.num = 5;
my.name = "Hello";
They will still show their original values in the list of: false, 0, and "".
If you really want to do this, you can do something like Jamie Dixon suggests.
Assuming that your list will always have an item at index 2:
private bool _isIt;
public List<object> mylist;
public bool isIt{
get{return _isIt;}
set{
_isIt = value;
myList[2] = value;
}
}
You use the value of isIt (default: false
) in the constructor, before you set the value of isIt on the row after. It will always default to false, unless you specifically change it, or change your logic. Because it is a value type, the value will be copied, not referenced.
mylist.Add(isIt);
Here you added a VALUE of isIt to the list, not the variable itself. thats why when you do:
my.isIt = true;
you update the variable, but the list will stay with old value.
my.mylist[2] is false, that's why it's returning false... could you clarify your question?
By declaring:
public bool isIt;
The default value will be false.
you could do:
public bool isIt = true;
to default it to true.
Setting my.isIt = true; after you've already added the default of false to the collection with mylist.Add(isIt); will not change the value of what you added at my.mylist[2]. You would need to set my.mylist[2] = true after already adding it to the list collection.
my.myList[2].isIt = true;
You didn't set the right item.
精彩评论