11.泛型的约束有哪几种
11.1 题目
泛型的约束有哪几种?
11.2 深入解析
在C#中,泛型允许我们编写更灵活和可重用的代码。为了限制泛型参数的类型,C#提供了多种约束类型。以下是C#中泛型的几种常见约束:
值类型约束:
T:struct- 要求泛型参数必须是值类型。
- 示例:
public class Example<T> where T : struct { // T必须是值类型 }
引用类型约束:
T:class- 要求泛型参数必须是引用类型。
- 示例:
public class Example<T> where T : class { // T必须是引用类型 }
公共无参构造函数约束:
T:new()- 要求泛型参数必须有一个公共的无参数构造函数。
- 示例:
public class Example<T> where T : new() { public T CreateInstance() { return new T(); } }
类约束:
T:类名- 要求泛型参数必须是指定的类或其派生类。
- 示例:
public class Example<T> where T : MyClass { // T必须是MyClass或其派生类 }
接口约束:
T:接口名- 要求泛型参数必须实现指定的接口。
- 示例:
public class Example<T> where T : IMyInterface { // T必须实现IMyInterface }
另一个泛型参数的约束:
T:U- 要求
T可转换为U(如T继承U或T实现接口U,依具体签名而定)。
- 要求
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,要求T与U满足可赋值关系(常见为继承或接口实现)。 notnull约束:where T : notnull(可空引用类型上下文)。
11.3 答题示例
“C# 泛型约束包括:
where T : struct要求值类型;where T : class要求引用类型;where T : new()要求公共无参构造函数;where T : 基类名要求继承指定类;where T : 接口名要求实现指定接口;where T : U要求T可赋值给U;where T : notnull(C# 8+)排除可空引用类型。
这样可以在编译期限制类型,提高代码安全性和可用性。”
11.4 关键词联想
- **
struct**(值类型约束) - **
class**(引用类型约束) - **
new()**(无参构造函数) - 基类约束(指定类或派生)
- 接口约束(实现接口)
- 泛型参数约束 (
T : U) - **
notnull**(可空引用类型上下文)
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com