Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#泛型可以有特定的基类型吗?_C#_Generics - Fatal编程技术网

C#泛型可以有特定的基类型吗?

C#泛型可以有特定的基类型吗?,c#,generics,C#,Generics,泛型接口的类型是否可能基于特定的父类 例如: public interface IGenericFace<T : BaseClass> { } IGenericFace公共接口 { } 显然,上面的代码不起作用,但如果它起作用,我想告诉编译器的是t必须是BaseClass的子类。这能做到吗?有计划吗 我认为它对于特定的项目很有用,确保在编译时泛型接口/类不会与意外类型一起使用。或者也可以对自我文档进行排序:显示所需的类型。公共接口IGenericFace其中T:SomeBaseC

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

例如:

public interface IGenericFace<T : BaseClass>
{
}
IGenericFace公共接口
{
}
显然,上面的代码不起作用,但如果它起作用,我想告诉编译器的是
t
必须是
BaseClass
的子类。这能做到吗?有计划吗

我认为它对于特定的项目很有用,确保在编译时泛型接口/类不会与意外类型一起使用。或者也可以对自我文档进行排序:显示所需的类型。

公共接口IGenericFace其中T:SomeBaseClass
public interface IGenericFace<T> where T : SomeBaseClass

IGenericFace公共接口
其中T:BaseClass
{
}

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

一些基本例子如下:

  • 其中T:struct
    -类型参数必须是值类型。可以指定除
    Nullable
    -之外的任何值类型。有关更多信息,请参阅

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

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

  • 其中T:
    -类型参数必须是或派生自指定的基类

  • 其中T:
    -类型参数必须是或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的

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

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

C#


你可以在@Kyralessa上找到更多关于如何约束类型的信息,有没有可能有一个泛型的BaseClass这个应该被删除,我看不出它是如何添加任何东西的-Kyralessa已经回答了这个问题。
public interface IGenericFace<T>
    where T : BaseClass
{
}
public class TestClass<T> where T : MyBaseClass, INotifyPropertyChanged, new() { }
public interface IGenericFace<T> where T : SomeBaseClass
Public Class TestClass(Of T As {MyBaseClass, INotifyPropertyChanged, New})
Public Interface IGenericInterface(Of T As SomeBaseClass)