Skip to main content
 首页 » 编程设计

c#之将来自同一基类的不同子类放入列表 C#

2024年02月06日18java哥

我想添加从同一基类扩展到列表中的不同子类。

所以这是基类:

public class InteractionRequirement { 
        protected int requirementNumber; 
 
        public int RequirementNumber{ 
            get{ return requirementNumber;} 
            set{ requirementNumber = value;} 
        } 
    } 

这些是子类:

public class ObjectInteraction : InteractionRequirement { 
    protected string objectName; 
    --getter and setter here-- 
} 
public class CharacterInteraction: InteractionRequirement { 
    protected string characterName; 
    --getter and setter here-- 
} 
public class AssetInteraction: InteractionRequirement { 
   protected string assetName; 
   --getter and setter here-- 
} 

然后我将它们添加到一个列表中:

List<InteractionRequirement> interactionRequirements = new List<InteractionRequirement>(); 
ObjectInteraction objectInteraction = new ObjectInteraction(); 
CharacterInteraction characterInteraction = new CharacterInteraction(); 
AssetInteraction assetInteraction = new AssetInteraction(); 
 
interactionRequirements.Add(objectInteraction); 
interactionRequirements.Add(characterInteraction); 
interactionRequirements.Add(assetInteraction); 

但我似乎无法从子类中检索属性值,出现错误。

string oName = interactionRequirement[0].ObjectName; 
string cName = interactionRequirement[1].CharacterName; 
string aName = interactionRequirement[2].AssetName; 

请您参考如下方法:

那是因为 interactionRequirements 集合属于 InteractionRequirement 类型,而不是派生类型(ObjectInteraction、CharacterIteraction 或 AssetInteraction)。

因此,您需要类型转换。

string oName = ((ObjectInteraction)interactionRequirement[0]).ObjectName; 

您还可以使用 as 并检查转换是否成功。

var objectInteraction = interactionRequirement[0] as ObjectInteraction; 
 
if (objectInteraction != null)  
{ 
   string oName = objectInteraction.ObjectName; 
} 

http://ideone.com/4giIL4

作为附加说明,您可能需要将 ObjectName 的保护级别更改为 public,以便您可以在适当的上下文中访问它(在类之外和派生的类)。