我有一个得到T: Item的列表的方法。如何从项的子类访问属性?
private void CreateShopItem<T>(Transform itemTemplate, Transform shopScrollView, List<T> shopItemList)
where T : Item {
shopItemList.Name //this works
shopItemList.power //this is a property from the class cooling and i cant access it
}从基类项中获得4个子类,但我只能访问类项中的属性
项目类别:
public class Item
{
public int Id;
public string Name;
public double Cost;
public Sprite Sprite;
public bool IsPlaced;
public Vector3 Position;
public Item()
{
Id = 0;
Name = "Default";
Cost = 0;
Sprite = null;
IsPlaced = false;
Position = Vector3.zero;
}
public Item(int id, string name, double cost, Sprite sprite, bool isPlaced, Vector3 position)
{
this.Id = id;
this.Name = name;
this.Cost = cost;
this.Sprite = sprite;
this.IsPlaced = isPlaced;
this.Position = position;
}
}亚级冷却:
public class Cooling : Item
{
public float power;
public float temp;
public Cooling(int id, string name, double cost, Sprite sprite, bool isPlaced, Vector3 position,
float power, float temp)
{
base.Id = id;
base.Name = name;
base.Cost = cost;
base.Sprite = sprite;
base.IsPlaced = isPlaced;
base.Position = position;
this.power = power;
this.temp = temp;
}
}从基类访问所有子类的属性的方法是什么?
发布于 2021-04-19 12:37:38
你要求代码做的事情是不合逻辑的。使用泛型类型时:
public class Foo<T>
{
public T Value { get; set; }
public void MyMethod()
{
// example code here
}
}您是说您将使用一个类型(T),但您还不能确定您将使用哪种类型。类型将在稍后阶段指定。编译器所做的唯一假设是,您的T将从object派生。
这是可以的,但这也意味着您实际上不能比使用T更精确地使用这个object。在上面的示例中,您可以调用this.Value.ToString(),因为T肯定是一个object ( object有ToString()方法),但是不能调用this.Value.Power,因为不知道T的类型是Cooling (或子类型)。
您能够影响编译器对T的特定类型的了解。您已经这样做了,指定T一定是某种类型的Item (即类或子类)。
public class Foo<T> where T : Item
{
public T Value { get; set; }
public void MyMethod()
{
// example code here
}
}因为现在期望T不仅仅是一个object,而且也是一个Item,所以编译器允许您使用Item类型的每个已知属性/方法来处理T类型。您可以访问以下内容:
this.Value.Name
this.Value.Cost
this.Value.Sprite因为这些是Item类的属性,您肯定可以在Item的任何子类上看到这些属性,所以在处理T where T : Item泛型类型参数时允许访问它们。
您试图访问特定类型的属性(Cooling),而没有告诉编译器您的泛型类型肯定是Cooling的(子)类。
这直接违背了使用泛型类型的核心前提,即使用相同的(泛型)代码处理一系列可能的类型。如果该泛型代码只处理一种特定类型(即Cooling),那么就没有必要尝试使CreateShopItem对任何不是Cooling或其子类型的类型起作用。
你需要带着你想要的东西回到画板上。
如果我可以假设CreateShopItem应该为任何Item类工作是正确的,那么您就应该能够编写能够处理任何Item对象的代码,而不需要知道所使用的具体类。
我故意忽略了向上转换,因为这是一个错误的方法,试图掩盖一个糟糕的设计。泛型向上转换很少是一个好主意。它违反了OCP (除了非常罕见的例子之外),而且在这个特定的场景中也不是一个好主意。
https://stackoverflow.com/questions/67161978
复制相似问题