.net 在运行时实现未定义列表

8i9zcol2  于 2023-03-31  发布在  .NET
关注(0)|答案(3)|浏览(116)

有没有办法在基类中实现List〈?〉?

public class DyanmoObject
{
   public int PlayerId { get; set; }
   public List<T> Objects
}

public class PlayerUnitDynamo : DynamoObject { }

public class PlayerBuildingDynamo : DynamoObject { }

public class PlayerBuilding
{
   public int BuildingID{ get; set; }
}

public class PlayerUnit
{
   public int UnitID{ get; set; }
}

public void AddItems()
{
   var unitDynamo = new PlayerUnitDynamo();
   unitDynamo.Objects.Add(new PlayerUnit());

   var buildingDynamo = new PlayerBuildingDynamo();
   buildingDynamo.Objects.Add(new PlayerBuilding());
}
myss37ts

myss37ts1#

您的问题中没有任何内容表明您在运行时之前没有该类型。
通过将DynamoObject变为DynamoObject<T>,您可以在编译时指定DynamoObject<T>的子类。

public class DynamoObject<T>
{
    public int PlayerId { get; set; }
    public List<T> Objects { get; set; } = new List<T>();
}

public class PlayerUnitDynamo : DynamoObject<PlayerUnit> { }

public class PlayerBuildingDynamo : DynamoObject<PlayerBuilding> { }

public class PlayerBuilding
{
    public int BuildingID { get; set; }
}

public class PlayerUnit
{
    public int UnitID { get; set; }
}

public void AddItems()
{
    var unitDynamo = new PlayerUnitDynamo();
    unitDynamo.Objects.Add(new PlayerUnit());

    var buildingDynamo = new PlayerBuildingDynamo();
    buildingDynamo.Objects.Add(new PlayerBuilding());
}
lp0sw83n

lp0sw83n2#

如果你要添加到列表中的东西真的彼此没有关系,你可以使用List<object>
想想它们有什么共同点。例如,也许它们在游戏中都有一个位置。你可以定义一个基类或接口来描述这种相似性,例如:

public interface IGameObject
{
    public double X { get; set; }
    public double Y { get; set; }
}

你可能会有

public class Chair : IGameObject
{
    // Implement the class
}

public class Pet : IGameObject
{
    // Implement the class
}

你就可以

List<IGameObject> objects = new List<IGameObject>();

objects.Add(new Pet());
objects.Add(new Chair());
wfauudbj

wfauudbj3#

你可以使用class对象来实现:

List<object> list = new List<object>();
list.Add(1);
list.Add("Hello");
foreach (var item in list)
    Console.WriteLine($"{item} - {item.GetType().Name.ToString()}");

console result

相关问题