开发者

Directly increasing an int in a List of objects

开发者 https://www.devze.com 2023-04-12 10:06 出处:网络
List<object> objects = new List<object>(); objects.Add(5); I want to do objects[0] += 10; But I need to cast it first.
List<object> objects = new List<object>();

objects.Add(5);

I want to do

objects[0] += 10;

But I need to cast it first.

int a = (int) objects[0];
a += 10;

But doing this only changes a, not the integer in the list.

开发者_开发问答

What's the best way to solve this?


You could do

objects[0] = ((int)objects[0]) + 10;


You can't directly increase the boxed integer that is stored in the list, because boxed structs are immutable. Jack Edmonds' solution is about as close as you can get.


have a list of integers instead ;p

List<int> objects = new List<int>();
0

精彩评论

暂无评论...
验证码 换一张
取 消