在C#中,如何拥有全局泛型类?

时间:2015-03-10 22:58:34

标签: c# generics inheritance

所以我有一组使用BaseEngine命名空间的抽象类,以及派生该组的真实游戏项目。

有许多基类具有一组抽象方法和预定义方法,例如: 项目,实体,技能

public abstract class Item 
{
    public string name;
    public void DestroyItemInBaseEngine () 
    {
        // bunch of codes
    }
    public abstract void BakeItemTheWayYouWant ();
}

public abstract class SkillManager
{
    public abstract T InteractItemWithSkill<T> (T item)
        where T:Item, new(); //not sure if this particular line is valid, but this was written just to help you understand
}

并派生出以下类:

public class GameItem : Item
{
    public int variableSpecificToThisGameProject;

    // and other implementation for this specific game...
}

现在,在BaseEngine中,它将具有在BaseItemManager等管理器中多次引用Item的抽象类。每个游戏都会有不同的管理方式,因此这些管理者也必须得到。当特定游戏项目派生BaseItemManager时,它必须使用GameItem。

创建BaseEngine是为了能够与不同的项目一起使用,这是一组基本的抽象类。

每次在游戏项目中引用这些派生对象时,您必须将其强制转换,或者在抽象方法中使用泛型类型:

if (ValidateItemObject<GameItem> (GameItem item) != null)
    // do something with it

因为GameItem和其他类型是在编译时决定的,无论如何都要为整个项目声明类似T = GameItem,S = GameSkill的东西,所以我们不必每次都提到相关的方法(如上所述) )或类被称为?

我尽力让我的案子尽可能清楚,但如果我不清楚我想要做什么,请告诉我。

编辑:

protected abstract T ConvertTableToItem<T> (T item, LuaTable luaTable) where T:BaseItem;


protected override ProjectItem SetItemAPI<ProjectItem> (ProjectItem newItem, LuaTable luaTable)
{
    newItem.desc = "test";
}

这并不能说desc不是班级成员。我可以保证。 desc(public string desc)在ProjectItem中定义。

ProjectItem是BaseItem的派生类。

1 个答案:

答案 0 :(得分:2)

如果要为泛型类型声明具有固定类型参数的类,最简单的方法是在指定所需的类型参数时继承泛型类型。例如:

static class SomeSpecificClass : SomeBaseClass<GameItem> { ... }

然后SomeBaseClass<T>中依赖于类型参数T的任何方法都可以通过SomeSpecificClass调用,而无需指定类型参数T

也就是说,工具箱中的另一个工具可能至少可以解决您提供的示例,即利用C#的泛型方法类型推断。

例如,如果您有这样的基类泛型方法:

class SomeBaseClass
{
    public static T ValidateItemObject<T>(T item) where T : Item
    {
        // ...something
    }
}

然后在调用方法时实际上不需要使用type参数,只要正确输入您传递的参数即可。例如:

GameItem gameItem = ...;

if (SomeBaseClass.ValidateItemObject(gameItem) != null)
{
    // ...something
}

(当然,如果代码在继承SomeBaseClass的类中,那么在调用方法时实际上不需要指定类名。)

不幸的是,您的实际代码示例相当模糊。但根据对问题的评论和你的回复,似乎上述内容应该解决你的问题。如果没有,请考虑编辑您的问题以提供a more specific, complete, but minimal code example,以及明确说明该示例现在执行的操作以及您希望如何更改。您可能还想阅读https://stackoverflow.com/help/how-to-ask,了解有关提高问题清晰度的提示。

相关问题