C#:VS System.Object的泛型 [英] C#: System.Object vs Generics

查看:154
本文介绍了C#:VS System.Object的泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很难理解时使用对象(装箱/拆箱)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 InvalidCastExceptions 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆