【问题标题】:C# How to instantiate inherited objects via a static method?C#如何通过静态方法实例化继承的对象?
【发布时间】:2019-10-12 19:48:38
【问题描述】:

我目前正在开发一个基于等距图块的游戏。目前,我有一个带有瓷砖的网格,这些对象包含有关它们的位置、类型和可以放置在它们顶部的各种对象(如树)的数据。

我创建了一个抽象的 TileObject 类,还有一个名为 Tree 的类继承自 TileObject。我的目标是拥有一个静态函数,它负责在不使用构造函数的情况下创建这些 TileObjects。

我也尝试过使用泛型(甚至使用 Activator 类),但似乎没有用。 我的想法是泛型、system.type、typeof,但我无法将这些全部放在一起。

public abstract class TileObject
{
    protected TileObject() { }

    public Tile Parent { get; set; }
    public string ObjectType { get; set; }

    public static TileObject CreateObject(string objName, Tile parent)
    {

    }
}

public class Tree : TileObject
{

}

我认为这个解决方案可以工作,但它似乎很难编码

public static TileObject CreateObject(string objName, Tile parent)
{
    TileObject x;
    if(objName == "Tree")
        x = new Tree();
    else if(objName == "Chair")
        ...
}

【问题讨论】:

  • 如何编写单独的方法,如CreateTreeCreateChair 等?

标签: c# unity3d grid tile


【解决方案1】:

一种解决方案可能是泛型!

这是一个例子:


public static TileObject CreateObject<T>(Tile parent) where T : TileObject, new()
{
    TileObject x = new T();
}

看看where T : TileObject, new()

这意味着你的类型 T TileObject,所以你甚至不必关心类型。

【讨论】:

  • ` 无法创建变量类型 'T' 的实例,因为它没有 new() 约束` 它这么说
  • 我刚刚编辑了答案,忘记了new() 约束
  • 您的回答是一个好的开始,但这看起来是一种错误的做事方式。这只是一个构造函数包装器,如果需要初始化过程听起来像统一应该提供的东西?
  • 您能详细解释一下您的目标吗?现在我很困惑
猜你喜欢
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多