You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Stack类传入null对象未抛出异常,求排查原因

问题分析与解决方案

你的代码逻辑本身是正确的:当Push方法接收null参数时,if (obj == null)的判断应该触发并抛出异常。问题出在Main方法中实例化的Stack对象并非你自定义的Stack类,而是.NET框架自带的System.Collections.Stack类——这个内置类的Push方法允许传入null,不会抛出异常。

解决步骤

  • 明确引用自定义类:如果你的自定义Stack类在某个命名空间下(比如MyApp),实例化时使用完整命名空间:
    var item1 = new MyApp.Stack();
    item1.Push(null);
    
  • 重命名自定义类:避免和内置类重名,比如把自定义类改为MyStack:
    public class MyStack
    {
        public readonly Stack<string> foodStack = new Stack<string>();
        public void Push(object obj)
        {
            if (obj == null)
            {
                throw new InvalidOperationException("You cannot add null to the stack");
            }
            string foodObject = obj.ToString();
            foodStack.Push(foodObject);
        }
    }
    
    然后Main方法中使用:
    MyStack item1 = new MyStack();
    item1.Push(null);
    
  • 使用别名区分:在文件顶部添加别名声明,明确指定自定义类:
    using CustomStack = 你的命名空间.Stack;
    
    实例化时:
    CustomStack item1 = new CustomStack();
    item1.Push(null);
    

额外提示

你的Push方法接收object类型参数后调用ToString(),如果传入非字符串类型的对象,会得到该对象的默认字符串表示(比如类型名)。如果只希望接收字符串类型,建议把参数改为string类型,这样更符合foodStack的Stack<string>类型:

public void Push(string obj)
{
    if (obj == null)
    {
        throw new InvalidOperationException("You cannot add null to the stack");
    }
    foodStack.Push(obj);
}

内容的提问来源于stack exchange,提问作者user18372316

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:53:13