C#enum为通用

时间:2017-10-01 11:56:41

标签: c# generics enums

干杯! 我有两个枚举,描述我的实体:玩家和枪支类型:

public enum PlayersType {
    Scout,
    Tank
}

public enum GunsType {
    Machinegun,
    Tesla
}

我有一个通用的结构泛型类,以及它的2个实现:

public class EntityType<T> where T: struct, IConvertible {
    public GameObjectType ObjectType;
}

public class PlayerEntity: EntityType<PlayersType> { }

public class TowerEntity: EntityType<GunsType> { }

我想创建具有EntityType字段并继承ScriptableObject类的类。

我这样做了:

public class ObjectTypeConfig: ScriptableObject
{
    public EntityType<Enum> EntityType;
}

但是它的返回错误:

  

“System.Enum”类型必须是非可空值类型才能在泛型类型或方法中将其用作类型参数“T”。

有谁知道如何创建必要的字段? 因此,我想创建一个Class,它将拥有一个ObjectTypeConfigs数组,包含玩家和塔的Entitiyes。

2 个答案:

答案 0 :(得分:2)

您将该属性声明为EntityType<Enum>,但EntityType的通用约束为EntityType<T> where T : struct

struct constraint表示:

  

type参数必须是值类型。可以指定除Nullable之外的任何值类型

如果您检查Enum,您会看到是一个类 - 因此可以分配null并且无法指定通用约束。

我怀疑你想要两个中的一个:

  1. 将属性更改为EntityType<GunsType>EntityType<PlayersType>
  2. 使用相同的约束使ObjectTypeConfig类通用,然后EntityType<T> EntityType

答案 1 :(得分:0)

public class ObjectTypeConfig<T>: ScriptableObject where T: struct, IConvertible
{
    public EntityType<T> EntityType;
}
相关问题