简体   繁体   English

C#:如何设计泛型类,以便type参数必须继承某个类?

[英]C#: How to design a generic class so that the type parameter must inherit a certain class?

I've written a class that looks like this: 我写了一个看起来像这样的课:

public class MyClass<T>
{
    public void doSomething()
    {
       T.somethingSpecial;
    }
}

This code doesn't compile because the compiler has no idea what T is. 此代码无法编译,因为编译器不知道T是什么。 I would like to constrain T so that it must inherit a certain class that defines somethingSpecial . 我想约束T,以便它必须继承某个定义somethingSpecial类。 Bonus points if you can tell me how to do the same thing by contraining T so that it must implement a certain interface. 如果你能告诉我如何通过限制T来做同样的事情以便它必须实现某个界面,那么奖励积分。

public class MyClass<T> where T: IAmSomethingSpecial

它被称为类型参数约束

Use the following type parameter constraint in the class declaration: 在类声明中使用以下类型参数约束:

public class MyClass<T> where T : MyBaseClass

You can read more about type parameter contraints for example here at MSDN . 您可以在MSDN上阅读有关类型参数约束的更多信息。

你想要的是一个通用约束

public class MyClass<T> where T : SomeParentClass

You need a Generic Constraint : 您需要通用约束

public class MyClass<T> where T : ISomeInterface
{
  public void doSomething()
  {
    instanceOfT.somethingSpecial();
  }
}

Read the documentation. 阅读文档。 Generic Constraint. 通用约束。

class MyClass<T> where T : someinterfaceorbaseclassthatTmustinherit
public interface ISomeInterface
{
    void DoSomething();
}

public class MyClass<T> where T : ISomeInterface
{
    public void doSomething()
    {
       T.DoSomething();
    }
}

The where keyword allows you to specify constraints on the given generic type. where关键字允许您指定给定泛型类型的约束。 You could swap out the interface for a class. 你可以换掉一个类的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 如何从抽象泛型 class 继承 class 并使用泛型 class 作为类型参数 - C# How to inherit class from abstract generic class with generic class as type parameter 如何从C#中的嵌套泛型类继承泛型类 - How to inherit a generic class from a nested generic class in C# 为什么非泛型派生类型必须为泛型基类C#指定类型参数 - why a non generic derived type must specify the type parameter for a generic base class C# 继承泛型类T必须是引用类型 - Inherit generic class T must be a reference type C# 泛型 class 与泛型参数相同的类型参数和约束 - C# generic class type parameter and constraint that is the same as the generic parameter 如何在 Blazor 中创建一个必须从具有泛型类型的类继承的泛型类型? - How to make a generic type that must inherit from a class with generic type in Blazor? c#获取泛型类中泛型类型参数的名称 - c# get the name of the generic type parameter in generic class 使用嵌套在泛型类中的类作为C#中的类型参数 - Using a class nested in a generic class as type parameter in C# 使用接口作为泛型类的类型参数,在C#中限制为“class” - Using a interface as a type parameter of generic class with the limitation of “class” in C# C#中具有通用类和接口的类设计 - Class Design with Generic Class and Interface in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM