-1

InterfaceA 包含 GetName 方法

InterfaceB 实现了接口 A 并包含 GetStatus 方法

foreach(InterfaceA item in tempList.getList()){
if(item is Interface B)
rootNode = new TreeNode(item.GetName);
rootNode.Tag = item
childNode = new TreeNode(item.GetStatus) <--**is this possible>? or is there any solution on getting instance with child interface from the parent?**
childNode.Tag = item
}
4

2 回答 2

3

当从父类/接口的引用访问子类/接口的方法时,您必须使用显式转换。当然,你必须确保演员阵容是合法的,if(item is Interface B)你的代码中受什么控制。

childNode = new TreeNode(((InterfaceB)item).GetStatus())
于 2013-07-29T03:54:47.650 回答
0

A easier solution is to use as instead of is. What as will do is return the interface if it can be cast or null if it can not.

foreach(InterfaceA item in tempList.getList())
{
    rootNode = new TreeNode(item.GetName());
    rootNode.Tag = item

    InterfaceB itemB = item as InterfaceB;
    if(itemB != null)
    {
        childNode = new TreeNode(itemB.GetStatus())
        childNode.Tag = itemB
    }
}
于 2013-07-29T04:05:16.477 回答