【问题标题】:Can C# generics have a specific base type?C# 泛型可以有特定的基类型吗?
【发布时间】:2008-10-23 17:56:50
【问题描述】:

泛型接口的类型是否可以基于特定的父类?

例如:

public interface IGenericFace<T : BaseClass>
{
}

显然上面的代码不起作用,但如果它起作用了,我想告诉编译器T 必须是BaseClass 的子类。能不能做到,有没有计划之类的?

我认为它对特定项目很有用,确保通用接口/类在编译时不与非预期类型一起使用。或者也用于某种自我记录:显示预期的类型。

【问题讨论】:

    标签: c# generics


    【解决方案1】:
    public interface IGenericFace<T> where T : SomeBaseClass
    

    【讨论】:

    【解决方案2】:

    您所指的是“通用约束”。可以对泛型类型施加许多约束。

    一些基本的例子如下:

    • where T: struct - 类型参数必须是值类型。可以指定除Nullable 之外的任何值类型。请参阅Using Nullable Types (C# Programming Guide) 了解更多信息。

    • where T : class - 类型参数必须是引用类型;这也适用于任何类、接口、委托或数组类型。

    • where T : new() - 类型参数必须具有公共无参数构造函数。当与其他约束一起使用时,new() 约束必须最后指定。

    • where T : &lt;base class name&gt; - 类型参数必须是或派生自指定的基类。

    • where T : &lt;interface name&gt; - 类型参数必须是或实现指定的接口。可以指定多个接口约束。约束接口也可以是通用的。

    • where T : U - 为T 提供的类型参数必须是或派生自为U 提供的参数。这称为裸类型约束。

    这些也可以像这样链接在一起:

    C#

    public class TestClass<T> where T : MyBaseClass, INotifyPropertyChanged, new() { }
    public interface IGenericFace<T> where T : SomeBaseClass
    

    VB

    Public Class TestClass(Of T As {MyBaseClass, INotifyPropertyChanged, New})
    Public Interface IGenericInterface(Of T As SomeBaseClass)
    

    【讨论】:

      【解决方案3】:

      是的。

      public interface IGenericFace<T>
          where T : BaseClass
      {
      }
      

      【讨论】:

      • 这应该被删除,我看不出它是如何添加任何东西的——Kyralessa 已经回答了这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      相关资源
      最近更新 更多