类型参数,它继承自某个抽象

时间:2012-11-20 15:40:28

标签: c# game-engine

我想知道是否有办法传入强制为某种基类型的类型。例如,对于我的游戏引擎,我有一个属性列表(可控制,rigidBody等)。我有一个addAttribute参数,它接受一个新对象。但是,我想有一个重载,它取一个类型,我可以自己创建一个新对象。所以例如

public void addAttribut(Type attribute)

我在考虑可能实现linq的东西?我试过但看起来“where”只能用于泛型:

public void addAttribute(Type attribute) where attribute : Attribute

将是该功能的签名。我相信Unity这样做;但它可能是通过Mono可以做到的。

如果它不是正确的基类型,我总是会抛出异常。但是,我想知道是否有办法阻止程序员在错误的时间内完成所有这些。

有什么想法吗?非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

如果您对调用代码需要知道编译时的类型感到高兴,可以使用类型参数使其成为通用方法:

public void AddAttribute<T>() where T : Attribute
{
    // Use typeof(T)
}

或者强制执行无参数构造函数,然后可以调用它:

public void AddAttribute<T>() where T : Attribute, new()
{
    T t = new T();
    ...
}

但是否则没有办法做到这一点,不 - 你必须在执行时验证参数,就像其他任何一样。