【问题标题】:What does <> mean when defining an interface?<> 在定义接口时是什么意思?
【发布时间】:2011-04-27 02:17:24
【问题描述】:

我正在学习编写自己的界面,并偶然发现了 MSDN 文章“Interfaces (C# Programming Guide)”。一切似乎都很好,除了: 是什么意思或做什么?

interface IEquatable<T>
{
    bool Equals(T obj);
}

【问题讨论】:

  • T代表Type,表示它是一个Generic接口,可以支持多种类型。

标签: c# .net class interface


【解决方案1】:

表示是generic接口。

你可以创建一个这样的界面:

public interface IMyInterface<T>
{
    T TheThing {get; set;}
}

您可以通过多种方式实现它:

public class MyStringClass : IMyInterface<string>
{
    public string TheThing {get; set;}
}

像这样:

public class MyIntClass : IMyInterface<int>
{
    public int TheThing {get; set;}
}

【讨论】:

  • 非常感谢。使用 T 有什么原因吗?
  • @eddy556:这只是一个约定 - T 用于表示“任何类型 T” - 但是,有时您会看到其他内容(即:Dictionary 等)跨度>
  • T 只是一个命名约定,因为通用参数名称引用了 _T_ype。您可以或多或少地命名它,但由于命名接口以 I 开头是一种约定,因此它也是命名以 T 开头的泛型类型参数的约定。在上面的示例中,它也可以具有被命名为TTheThing 或类似的东西。
【解决方案2】:

它是一个参数类型意味着您可以将 IEquatable 用于任何类型...在“运行时”(但不完全是),您可以使用 String、Animal、Dog ecc 代替 T...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2022-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多