【问题标题】:Put different subclasses from the same base class into a list C#将来自同一基类的不同子类放入列表 C#
【发布时间】:2015-09-22 01:48:15
【问题描述】:

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

所以这是基类:

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;

【问题讨论】:

    标签: c# .net subclass superclass


    【解决方案1】:

    这是因为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,以便您可以在适当的上下文中访问它(在类和派生类之外)。

    【讨论】:

    • 值得注意的是,无论如何都不能保证element[0] 将始终是ObjectInteraction,因为您可以删除和插入元素......所以即使这可以解决错误它不是一个长期的解决方案(基类名称或创建一个GetName 方法)
    • @mattytommo - 努力跟上你的步伐,m8! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多