gpt4 book ai didi

c# - 简单继承不起作用?

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:07 24 4
gpt4 key购买 nike

我似乎忘记了一些最基本的继承规则,因为我想不通为什么这行不通。我有一个扩展 Node 的类 SuffixNode。

节点:

class Node
{
public char label;
public Node parent;
public Dictionary<char,Node> children;

public Node(Node NewParent, char NewLabel)
{
this.parent = NewParent;
this.label = NewLabel;
children=new Dictionary<char,Node>();
}
}

后缀节点:

class SuffixNode: Node
{
public Dictionary<String, int> Location=new Dictionary<String, int>();

public SuffixNode(Node NewParent):base(NewParent, '$')
{

}

public void AddLocation(String loc,int offset)
{
this.Location.Add(loc, offset);
}
}

我试图从 SuffixNode 类调用主程序中的 AddLocation 方法,但它给我一个错误,指出不存在这样的方法(在 Node 类中):

Node n;
char FirstChar = suffix[0]; //first character of the suffix
if (suffix == "")
{
return true;
}

//If the first character of a suffix IS NOT a child of the parent
if (!parent.children.ContainsKey(FirstChar))
{
if (FirstChar == '$')
{
n = new SuffixNode(parent);
n.AddLocation(document, offset);
}
else
{
n = new Node(parent, FirstChar); //Create a new node with the first char of the suffix as the label
parent.children.Add(FirstChar, n); //Add new node to the children collection of the parent
}
}

我确信这是一个非常简单的答案,但我就是不明白为什么这不起作用。不应该

Node n = new SuffixNode(parent)

允许我访问 SuffixNode 方法和变量吗?

最佳答案

您已将 n 的类型声明为 Node,实际上它没有 AddLocation 方法。您必须将其声明为 SuffixNode n = new SuffixNode(parent) 才能在其上调用子函数,或者向 Node 添加一个(可能是抽象的)方法称为 AddLocation

关于c# - 简单继承不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9742504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com