11.泛型的约束有哪几种

  1. 11.泛型的约束有哪几种
    1. 11.1 题目
    2. 11.2 深入解析
      1. 示例代码
      2. 总结
    3. 11.3 答题示例
    4. 11.4 关键词联想

11.泛型的约束有哪几种


11.1 题目

泛型的约束有哪几种?


11.2 深入解析

在C#中,泛型允许我们编写更灵活和可重用的代码。为了限制泛型参数的类型,C#提供了多种约束类型。以下是C#中泛型的几种常见约束:

  1. 值类型约束T:struct

    • 要求泛型参数必须是值类型。
    • 示例:
      public class Example<T> where T : struct
      {
          // T必须是值类型
      }
      
  2. 引用类型约束T:class

    • 要求泛型参数必须是引用类型。
    • 示例:
      public class Example<T> where T : class
      {
          // T必须是引用类型
      }
      
  3. 公共无参构造函数约束T:new()

    • 要求泛型参数必须有一个公共的无参数构造函数。
    • 示例:
      public class Example<T> where T : new()
      {
          public T CreateInstance()
          {
              return new T();
          }
      }
      
  4. 类约束T:类名

    • 要求泛型参数必须是指定的类或其派生类。
    • 示例:
      public class Example<T> where T : MyClass
      {
          // T必须是MyClass或其派生类
      }
      
  5. 接口约束T:接口名

    • 要求泛型参数必须实现指定的接口。
    • 示例:
      public class Example<T> where T : IMyInterface
      {
          // T必须实现IMyInterface
      }
      
  6. 另一个泛型参数的约束T:U

    • 要求 T 可转换为 U(如 T 继承 UT 实现接口 U,依具体签名而定)。
  7. notnull 约束(C# 8+)where T : notnull

    • 禁止可空引用类型作为 T(配合可空引用上下文使用)。
    • 示例:
      public class Example<T> where T : notnull
      {
          // T 不可为 string? 等可空引用类型(在启用可空上下文中)
      }
      

示例代码

using System;

public class Example<T> where T : class, new()
{
    public void PrintType()
    {
        T instance = new T();
        Console.WriteLine("类型: " + instance.GetType().Name);
    }
}

public interface IMyInterface { }

public class MyClass : IMyInterface
{
    public MyClass() { }
}

public class Program
{
    public static void Main()
    {
        // 使用带有泛型约束的类
        Example<MyClass> example = new Example<MyClass>();
        example.PrintType(); // 输出: 类型: MyClass
    }
}

总结

  • 值类型约束T:struct,要求泛型参数必须是值类型。
  • 引用类型约束T:class,要求泛型参数必须是引用类型。
  • 公共无参构造函数约束T:new(),要求泛型参数必须有一个公共无参数构造函数。
  • 类约束T:类名,要求泛型参数必须是指定类或其派生类。
  • 接口约束T:接口名,要求泛型参数必须实现指定接口。
  • 另一个泛型参数的约束T:U,要求 TU 满足可赋值关系(常见为继承或接口实现)。
  • notnull 约束where T : notnull(可空引用类型上下文)。

11.3 答题示例

“C# 泛型约束包括:

  1. where T : struct 要求值类型;
  2. where T : class 要求引用类型;
  3. where T : new() 要求公共无参构造函数;
  4. where T : 基类名 要求继承指定类;
  5. where T : 接口名 要求实现指定接口;
  6. where T : U 要求 T 可赋值给 U
  7. where T : notnull(C# 8+)排除可空引用类型。
    这样可以在编译期限制类型,提高代码安全性和可用性。”

11.4 关键词联想

  • **struct**(值类型约束)
  • **class**(引用类型约束)
  • **new()**(无参构造函数)
  • 基类约束(指定类或派生)
  • 接口约束(实现接口)
  • 泛型参数约束 (T : U)
  • **notnull**(可空引用类型上下文)


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com

×

喜欢就点赞,疼爱就打赏