[英]C# Any substitutes for Boxing/Unboxing?
My recent code is including a lot of boxing and unboxing , as many of my variables are resolved at runtime.我最近的代码包括很多装箱和拆箱,因为我的许多变量都是在运行时解析的。 But I've read that boxing and unboxing is very expensive computationally, and so I want to ask if there is any other ways to box/unbox types?
但是我读过装箱和拆箱在计算上非常昂贵,所以我想问一下是否有其他方法来装箱/拆箱类型? And is this even a good practice to use it?
这甚至是使用它的好习惯吗?
Use Generics
....使用
Generics
....
For example例如
List lst=new List();//non generic List accepts any kind of object
lst.Add(44);//this causes unnecessary boxing from int to object
lst.Add(100);//this causes unnecessary boxing from int to object
If you are sure that the list will always contain an integer you can use generics..如果您确定该列表将始终包含一个整数,您可以使用泛型..
List<int> lst=new List<int>();
lst.Add(44);//no boxing or unboxing
lst.Add(100);//no boxing or unboxing
In that specific question I could say use the more general type, in that case string and parse it to number if its a number.在那个特定问题中,我可以说使用更通用的类型,在这种情况下是字符串,如果它是数字,则将其解析为数字。 More general approch is to create custom struct or use tuple with field stating what its the real answer for each case like that , but its quit ugly.
更一般的方法是创建自定义结构或使用带有字段的元组,说明每个案例的真正答案是什么,但它很难看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.