c# - 无法访问自定义类堆栈实现中的类

标签 c#

我的类结构如下:

public abstract class LogicalTreeNode {
}

public class LogicalOperator:LogicalTreeNode {
    public readonly string value;

    public LogicalOperator(string value) {
        this.value = value;
    }

}

public class ConditionResult:LogicalTreeNode {
    public readonly bool value;

    public ConditionResult(bool value) {
        this.value = value;
    }
}`

我正在尝试使用 Stack<LogicalTreeNode> 来实现一些逻辑.我需要标准堆栈的方法和我自己的 TryPush(LogicalTreeNode) ,这将递归工作(对于某些情况)。所以我这样做:

public class Stack<LogicalTreeNode> : Stack {
    public void TryPush(LogicalTreeNode logicalTreeNode) {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

然后我得到 cannot convert ConditionResult to LogicalTreeNode .我在做什么? TIA。

最佳答案

您已经创建了一个自定义类 Stack通用于 System.Collections.Stack接受 Stack<LogicalTreeNode> .

将您的代码更改为此-

public class Stack<T> : Stack
{
    public void TryPush(LogicalTreeNode logicalTreeNode)
    {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

如果您特别希望您的类仅使用特定类型进行实例化,例如- LogicalTreeNode在这种情况下,您必须这样做-

public class MyStack<T> where T : LogicalTreeNode
{
    public void TryPush(LogicalTreeNode logicalTreeNode)
    {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

如果需要继承System.Collections.Stack类并将类型限制为 LogicalTreeNode , 然后这样做-

public class MyStack<T> : System.Collections.Stack : where T : LogicalTreeNode
{
    public void TryPush(LogicalTreeNode logicalTreeNode)
    {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

另外,作为一种好的做法,不要将您的类(class)命名为 Stack因为它是 C# 关键字。使用不同的名称。

引用资料:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-classes

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters

关于c# - 无法访问自定义类堆栈实现中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49838437/

相关文章:

c# - 我可以使用带有 params 关键字的 lambda 表达式吗?

c# - 使 Web 服务更快 (wcf)

c# - 使用 NetTcpBinding 在 WCF 中找出所需的 MaxReceivedMessageSize

c# - P/Invoke 声明似乎不正确

c# - 如何在 c#.net windows 应用程序中生成日历

c# - Visual Studio 2015 和 IFormatProvider 中的字符串插值 (CA1305)

c# - 匿名类型的平等

c# - 模拟 Controller 上下文 asp 4.5

c# - .Net 观察者模式改变。这些是什么时候发生的,为什么?

c# - 使用 PDFSharp 时访问 Azure Web App 中的字体时出错