c# 泛型约束

在C#中,泛型约束用于指定泛型类型参数的限制条件,以确保类型参数满足特定的条件。以下是C#中常见的泛型约束:

where T : struct: 这个约束要求类型参数必须是一个值类型(如int、float等)。

where T : class: 这个约束要求类型参数必须是一个引用类型(如类、接口、委托等)。

where T : new(): 这个约束要求类型参数必须具有一个无参数的公共构造函数。

where T :: 这个约束要求类型参数必须是指定的基类或派生自指定的基类。

where T :: 这个约束要求类型参数必须实现指定的接口。

where T : U: 这个约束要求类型参数必须与指定的类型参数(U)相同,或者是从指定的类型参数(U)派生的类型。

这些约束可以单独使用,也可以组合使用。例如,下面的示例演示了如何使用多个约束:

csharp 复制代码
public interface IExampleInterface
{
    void ExampleMethod();
}
//ExampleClass的泛型必须要实现IEampleInterface的接口,且默认带无参构造函数
public class ExampleClass<T> where T : IExampleInterface, new()
{
    public void ExampleMethod(T exampleObject)
    {
        exampleObject.ExampleMethod();
    }
}

public class ExampleImplementation : IExampleInterface
{
    public void ExampleMethod()
    {
        Console.WriteLine("ExampleMethod called");
    }
}

static void Main(string[] args)
{
    ExampleClass<ExampleImplementation> example = new ExampleClass<ExampleImplementation>();
    example.ExampleMethod(new ExampleImplementation());
}

在这个示例中,ExampleClass是一个泛型类,使用了两个约束:where T : IExampleInterface 约束类型参数必须实现 IExampleInterface 接口,where T : new() 约束类型参数必须具有无参数的公共构造函数。通过使用泛型约束,可以确保类型参数满足特定的条件,从而在编译时捕获错误并提供更安全和可靠的代码。

相关推荐
lqj_本人1 分钟前
深入解析Qt for OpenHarmony的CMake构建系统与常见陷阱
开发语言·qt
n***29321 分钟前
PHP安全编程实践
开发语言·安全·php
b***748824 分钟前
PHP在电子商务系统中的构建
开发语言·php
岚天start34 分钟前
Java程序生成Heap Dump堆内存快照文件的多种方法
开发语言·python·pycharm
天马行空-1 小时前
ES 精准匹配 和 模糊查询的实现方式
java·开发语言
Z***25801 小时前
Java计算机视觉
java·开发语言·计算机视觉
Tiger_shl1 小时前
SqlConnection、SqlCommand 和 SqlDataAdapter
开发语言·数据库·c#
一点事1 小时前
ruoyi:集成mybatisplus实现mybatis增强
java·开发语言·mybatis
你的冰西瓜1 小时前
C++14 新特性详解:相较于 C++11 的主要改进
开发语言·c++·stl
linksinke1 小时前
Mapstruct引发的 Caused by: java.lang.NumberFormatException: For input string: ““
java·开发语言·exception·mapstruct·numberformat·不能为空