C#:VS System.Object的泛型 [英] C#: System.Object vs Generics
问题描述
我有一个很难理解时使用对象(装箱/拆箱)VS时使用泛型
I'm having a hard time understanding when to use Object (boxing/unboxing) vs when to use generics.
例如:
public class Stack
{
int position;
object[] data = new object[10];
public void Push (object o) { data[position++] = o; }
public object Pop() { return data[--position]; }
}
VS
VS.
public class Stack<T>
{
int position;
T[] data = new T[100];
public void Push(T obj) {data[position++] = obj; }
public T Pop() { return data[--position]; }
}
哪一个我应该使用以及在什么条件?这似乎是与System.Object的方法可以让我有各种各样的目前生活我的堆栈中类型的对象。所以,这是不是可以始终是最好?谢谢!
Which one should I use and under what conditions? It seems like with the System.Object way I can have objects of all sorts of types currently living within my Stack. So wouldn't this be always preferable? Thanks!
推荐答案
的总是的使用泛型!铸造业务和价值类型的装箱/拆箱使用对象的结果。由于这些原因仿制药更快,更优雅(无铸造)。和 - 主要的原因 - 你不会得到 InvalidCastException的
S使用泛型
Always use generics! Using object's results in cast operations and boxing/unboxing of value-types. Because of these reasons generics are faster and more elegant (no casting). And - the main reason - you won't get InvalidCastException
s using generics.
因此,仿制药更快,错误是在编译时可见。 System.Object的
指运行时异常和铸造这在一般导致较低的性能(有时要低得多)。
So, generics are faster and errors are visible at compile-time. System.Object
means runtime exceptions and casting which in general results in lower performance (sometimes MUCH lower).
这篇关于C#:VS System.Object的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!