【问题标题】:Why Use <T> in C#? [duplicate]为什么在 C# 中使用 <T>? [复制]
【发布时间】:2013-06-04 14:22:04
【问题描述】:

最近我遇到了下面的代码。

public interface IBlog<T>
{            
     void Add(T blog);
     IEnumerable<T> GetAll();
     T GetRecord(int id);
     void Delete(int id);          
}

这里的T 是什么?使用它的目的是什么?

【问题讨论】:

标签: c# asp.net .net


【解决方案1】:

一个简单的例子,你可以有一个方法

T GetDefault<T>()
{
    return default(T);
}

然后打电话

int zero = GetDefault<int>();

方法中的T 将是int 的类型。

c# 中有List&lt;int&gt;List&lt;string&gt;,例如,这是在using generics, read more... 中实现的

【讨论】:

    【解决方案2】:

    您想知道的是Generics。泛型提供了一种很好的动态处理方式。您可能已经知道也可能不知道,但ListDictionary 使用泛型。

    List<Foo> foos = new List<Foo>(); //Means everything within that list will be of Foo type
    List<Bar> bars= new List<Bar>(); //Again, means everything within that list will be of Bar type
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2015-07-29
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      相关资源
      最近更新 更多