Skip to main content
 首页 » 编程设计

c#之我可以定义一个 Type 变量,表示特定类的子类型的类型是唯一有效值吗

2024年02月13日12jirigala

背景

我正在为一个小型个人游戏项目编写一些组件 ( this kind of component)。在该系统中,实体具有属于不同类别的各种类型的组件。例如,IController 组件类别包括 KeyboardController 和 AiController。一个实体有一组组件,每个类别应该只有一个组件。所有组件都继承自 IComponent。

组件有一个 MetaType 属性,它应该报告它们对应的类型,以便说:“嘿,请把我当作这种类型的组件!”此属性返回一个 Type 对象。 AiController 返回 typeof(IController),告诉实体将其视为其 Controller 。其他有效的元类型是 typeof(AiController) 或 typeof(IComponent)。它不应该能够返回任何任意类型,例如typeof(int) - 只是组件类型。

我的问题

目前,我的组件可以报告 MetaType 的任意类型。例如,AIController 实际上可以返回 typeof(int) - 毕竟这是一个有效的 Type 对象。

我能否限制 Type 值,使唯一有效的类型是 IComponent 是其祖先的任何类或接口(interface)的类型?我想这样的变量声明可能是这样的:

Type<IComponent> component; // This can only store certain types 
Type where Type : IComponent component; // This too 

我特别感兴趣的是这是否可行 - 替代方法并不多(我知道有几种方法,它们包括只允许这种行为,因为我是唯一一个使用这段代码。

请您参考如下方法:

您可以创建一个 MetaType其构造函数或工厂方法将采用针对 IComponent 约束的泛型类型的对象并提供对非约束 Type 的访问.但由于它的构造函数受到限制,您应该保证不会获得其他非 IComponent。

public class MetaType 
{ 
    public Type ComponentType { get; private set; } 
 
    private MetaType(Type componentType) 
    { 
        this.ComponentType = componentType; 
    } 
 
    public static MetaType Create<T>() where T : IComponent 
    { 
        return new MetaType(typeof(T)); 
    } 
} 

您的用法可能如下所示:

MetaType validType = MetaType.Create<IComponent>(); //fine 
MetaType validType = MetaType.Create<IController>(); //fine 
MetaType validType = MetaType.Create<AIController>(); //fine 
 
MetaType invalidType = MetaType.Create<int>(); //compiler error! 

编辑:我假设您的 IController接口(interface)继承自IComponent , 但如果没有,您可以添加工厂重载,如 CreateController和 CreateComponent每一个都受制于唯一的界面。