首页 文章

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

提问于
浏览
1

背景

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

组件具有MetaType属性,该属性应报告它们对应的类型,以便说:"Hey, please treat me as this type of component!"此属性返回Type对象 . AiController返回typeof(IController),告诉实体将其视为其控制器 . 其他有效的元类型将是typeof(AiController)或typeof(IComponent) . 它不应该能够返回任何类型,例如typeof(int) - 只是组件类型 .

我的问题

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

我可以约束Type值,以便唯一有效的类型是IComponent是祖先的任何类或接口的类型吗?我想这样的变量声明可能如下所示:

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

I am specifically interested in whether this is possible - 在替代方法中没有那么多(我知道几个,它们只包括允许这种行为,因为我是唯一一个使用此代码的人 .

2 回答

  • 1

    您可以创建一个 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 接口继承自 IComponent ,但如果没有,您可以添加工厂重载,如 CreateControllerCreateComponent ,每个都受限于独特的接口 .

  • 3

    不幸的是,不是直接的 - 虽然你可以在泛型中约束类型参数,但是像 MetaType 字段这样的类型变量基本上就像试图约束 int 一样:你可以使用异常来确保它永远不会被设置为无效值但最终变量本身可以是任何正确的类型 .

相关问题