在 c# 中取消装箱时出现错误,指出名称在当前上下文中不存在?

getting an error in unboxing in c# stating name does not exist in current context?

  class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("enter id");
            int id = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("enter name");
            string name = Console.ReadLine();
            Console.WriteLine("price");
            int price = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("enter quantity");
            int quantity = Convert.ToInt32(Console.ReadLine());
            product_demo p1 = new product_demo(id, name, price, quantity);
            p1.diplay();
            Console.Read();
        }
    }
    public class product_demo
    {
        public int id;
        public string name;
        public int price;
        public int quantity;
        public product_demo(int id, string name, int price, int quantity)
        {
            this.id = id;
            this.name = name;
            this.price = price;
            this.quantity = quantity;
            object o1 = id;
            object o2 = name;
            object o3 = price;
            object o4 = quantity;

        }
   
        public void diplay()
        {
            int j = (int)o1; 
            Console.WriteLine("id :");
        }
    }

在显示功能中拆箱时出现错误。装箱在 product_demo 构造函数中完成。还有一个问题 ;我们可以在任何构造函数或方法之外直接在 class.

的主体中定义装箱吗

您在 product_demo 的构造函数中创建了 object o1,因此它仅存在于该范围内。您需要将对象放在 class 中(类似于放置其他变量的位置,例如 int idstring name