Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

boxing - 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 :");
        }
    }

getting an error while unboxing in display function. boxing is done in product_demo constructor. one more question ; can we define boxing outside any constructor or methods, directly in body of class.

question from:https://stackoverflow.com/questions/65912587/getting-an-error-in-unboxing-in-c-sharp-stating-name-does-not-exist-in-current-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have created object o1 in the constructor of product_demo and therefore it exists only within that scope. You need to have your objects within the class (Similar to where you have placed your other variables such as int id, string name, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...