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

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

问题描述

我很难理解何时使用对象(装箱/拆箱)与何时使用泛型.

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.

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#:System.Object 与泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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