【问题标题】:C#: How to design a generic class so that the type parameter must inherit a certain class?C#:如何设计一个泛型类,使得类型参数必须继承某个类?
【发布时间】:2011-12-22 15:29:42
【问题描述】:

我编写了一个如下所示的类:

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

此代码无法编译,因为编译器不知道 T 是什么。我想限制 T 使其必须继承定义somethingSpecial 的某个类。如果你能告诉我如何通过约束 T 来做同样的事情,那么它必须实现特定的接口。

【问题讨论】:

  • C# 使用泛型,而不是模板。

标签: c# .net class generics


【解决方案1】:
public class MyClass<T> where T: IAmSomethingSpecial

它叫Constraints on Type Parameters

【讨论】:

    【解决方案2】:

    在类声明中使用以下类型参数约束:

    public class MyClass<T> where T : MyBaseClass
    

    您可以阅读有关类型参数约束的更多信息,例如 here at MSDN

    【讨论】:

      【解决方案3】:

      你想要的是generic constraint:

      public class MyClass<T> where T : SomeParentClass
      

      【讨论】:

        【解决方案4】:

        你需要一个Generic Constraint:

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

        【讨论】:

          【解决方案5】:
          public interface ISomeInterface
          {
              void DoSomething();
          }
          
          public class MyClass<T> where T : ISomeInterface
          {
              public void doSomething()
              {
                 T.DoSomething();
              }
          }
          

          where 关键字允许您对给定的泛型类型指定约束。你可以把接口换成一个类。

          【讨论】:

            【解决方案6】:

            阅读文档。通用约束。

            class MyClass<T> where T : someinterfaceorbaseclassthatTmustinherit
            

            【讨论】:

              猜你喜欢
              • 2014-12-19
              • 2012-08-30
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-11-18
              • 1970-01-01
              • 2023-01-17
              相关资源
              最近更新 更多