where关键词一个最重要的用法就是在泛型的声明、定义中做出约束。 约束又分为接口约束、基类约束、构造函数约束、函数方法的约束,接下来我们通过代码来一一介绍这些约束
where 泛型接口约束
泛型接口约束那就是参数必须实现相应的接口才可以,下面用代码展示一下:
//接口定义
public interface ICarFactory
{
string Name
{
get;
}
string Type
{
get;
}
}
//实现接口的类
public class Car : ICarFactory
{
private string name;
public string Name
{
get
{
return name;
}
}
private string type;
public string Type
{
get
{
return type;
}
}
public Car():this("jiaoche", "AD")
{
}
public Car(string name = "1", string type = "2")
{
this.name = name;
this.type = type;
}
}
//泛型约束,Where 后面的 T 一定要是实现了接口 ICarFactory 的类或者是接口 ICarFactory
using UnityEngine;
public class InterfaceTest<T> where T : ICarFactory
{
public InterfaceTest()
{
Debug.Log("=====构造方法被调用=====");
}
}
using UnityEngine;
//测试接口泛型的类
public class CarFactoryTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//成功,Car实现了ICarFactory接口
InterfaceTest<Car> mc1 = new InterfaceTest<Car>();
Debug.Log("11111111=="+mc1.GetType());
InterfaceTest<ICarFactory> mc2 = new InterfaceTest<ICarFactory>();
Debug.Log("22222222=="+mc2.GetType());
//构造失败,string没有实现ICarFactory接口,编译器提示错误
// InterfaceTest<String> mc3 = new InterfaceTest<String>();
}
// Update is called once per frame
void Update()
{
}
}
测试结果打印如下图:
where 泛型类约束以及构造约束一起讲解
using UnityEngine;
public class DriveCar : Car
{
public DriveCar()
{
Debug.Log("对应 new 无参数的构造函数,否则会报错");
}
public DriveCar(int a,int b) {
Debug.Log("DriveCar 构造函数被调用");
}
}
using UnityEngine;
//T 约束是类 DriveCar
public class DriveCarTest<T> where T : DriveCar, new()
{
public DriveCarTest()
{
Debug.Log("=====DriveCarTest 类约束构造函数被调用=====");
}
}
//泛型类约束测试
DriveCarTest<DriveCar> car1 = new DriveCarTest<DriveCar>();
Debug.Log("333333333==" + car1.GetType());
//错误的泛型参数
// DriveCarTest<ICarFactory> errCar = new DriveCarTest<ICarFactory>();
测试类约束结果
总结
where T : struct 这表明T必须是一个值类型,像是int,decimal这样的
where T : class 这表明T必须是一个引用类型,像是自定义的类、接口、委托等
where T : new() 这表明T必须有无参构造函数,且如果有多个where约束,new()放在最后面
where T : [基类] 这表明T必须是base class类获其派生类
where T : [接口] 这表明T必须实现了相应的接口
如果还需要拓展可继续查看如下文档: