将同一基类中的不同子类放入列表C#中

时间:2015-07-04 11:22:15

标签: c# .net subclass superclass

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

所以这是基类:

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;

但我似乎无法从子类中检索属性值,这是一个错误。

devices = [[NSMutableArray alloc] init];
dataFields = [[NSArray alloc] initWithObjects:@"Name",@"Type", nil];

NSArray *addDevice = [[NSArray alloc] initWithObjects:@"MM-TEST",@"-- --", nil];
NSDictionary *infoblock = [[NSMutableDictionary alloc] initWithObjects:addDevice forKeys:dataFields];
[devices addObject:infoblock];

1 个答案:

答案 0 :(得分:4)

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