c# - 在 C# 中,类名介于 "Less than"和 "Greater than"符号之间的目的是什么?

标签 c# class generics declaration

我不明白下面的类声明:

public abstract class Class1 <TDomainServiceContract, TDomainService>
{
   ...
}

我知道什么TDomainServiceContractTDomainService是,但为什么在 < 之间使用它们和 >符号?

最佳答案

<之间的参数和 >是泛型类型参数。泛型在非常高的层次上允许您设计一个类,该类对其一个或多个参数、属性或方法的特定类型是不可知的。用文字来解释有点困难,但泛型最常见的用途是在集合中。

在泛型之前,大多数开发人员使用像 ArrayList 这样的东西跟踪对象的集合。这样做的缺点是安全;因为你可以放任何 objectArrayList ,这意味着您必须将您的对象转换回预期的类型(使代码不那么干净),并且您没有什么可以阻止您添加不是那种类型的对象的东西(即我可以有一个 ArrayList,我可能期望只包含 string 对象,但我可能——不小心——放入了一个 int 或一个 DbConnection 等),你永远不会发现,直到转换失败时的运行时。

ArrayList myStrings = new ArrayList();

myStrings.Add("foo");
myStrings.Add("bar");
myStrings.Add(1); // uh-oh, this isn't going to turn out well...

string string1 = (string)myStrings[0];
string string2 = (string)myStrings[1];
string string3 = (string)myStrings[2]; // this will compile fine but fail at 
                                       // runtime since myStrings[2] is an int, 
                                       // not a string

引入泛型后,我们得到了List<T>类(class)。这是一个采用单个泛型类型参数的单一类——即您希望列表包含的对象类型。这样,我就可以得到一个 List<string>List<int>那将 a) 不需要转换,因为索引器返回 stringint , 和 b) 在编译时是安全的,因为我知道除了 string 之外别无他物。或 int (再次,分别)可以放入这些列表中。

List<string> myStrings = new List<string>();

myStrings.Add("foo");
myStrings.Add("bar");
myStrings.Add(1); // this will not compile, as an int is not a string

泛型的要点是说您不关心您正在使用的对象的实际 类型是什么,但您的类的使用者可能会关心。换句话说,列表如何存储 string 的机制。 , 一个 int , 一个 DbConnection等是相同的,但是泛型使得来自您类的使用者的这种类型信息不会在您的抽象中丢失。

关于c# - 在 C# 中,类名介于 "Less than"和 "Greater than"符号之间的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516358/

相关文章:

c# - 接口(interface)中的类型约束适用于基类

c# - 如何通过代码在一个实例中创建 .NET 程序的另一个实例?

class - typescript 类 : "Overload signature is not compatible with function implementation"

class - Swift 中结构体和类的区别

c# - 如何获得扩展方法来更改原始对象?

java - 了解内部泛型类

c# - 在具有原始类型的参数的修饰符中使用 C# 7.2

c# - 在 Response.Redirect 中移除对象移动的 HTML

c# - DynamicData - 无法将静态方法移动到另一个类(甚至基类)

使用 xCode 5.1.1 进行 iOS 编程