Passing variables from Main function to another C# class

前端 未结 4 618
轮回少年
轮回少年 2021-01-21 07:56

I\'m beating my head against the wall pretty severely with this. I have several variables inside a C# console application that I would like to re-use. However, I cannot for th

4条回答
  •  有刺的猬
    2021-01-21 08:29

    If the variable denote some information about an object (like name, id, etc.) then they should be encapsulated in a class. The instance of the class (called an object) should be used to access this information.

    As you already have the variables that represent an object, the next step would be to group these variables into classes. These variables are represented as properties in the class. The operations performed on these members should be available as methods. Furthermore the access modifiers decide the visibility of the members.

    Going through your example, I can identify 3 variables that represent a Customer (assumption, I am not sure of the exact use case). These will form the Customer class.

    class Customer
    {
        // You can either pass the UID through the constructor or 
        // expose a public setter to allow modification of the property
        public Customer(string uid)
        {
            this.UID = uid;
        }
    
        public string UID { get; private set; }
        public string Name { get; set; }
        public string Count { get; set; }
    }
    

    Furthermore, the foreach loop can be split into 2 parts for resuablity

    1. Read from the xml nodes and create a list of customers
    2. Perform the database operations (like trigger stored procedures, write values, etc.) on the list of customers

    Additionally, you can create another class that does the operations (business logic) that you are performing in the console application. This will allow you to reuse the same logic in case you move it to another application (like winforms or web service).

    More information

    • Object oriented programming
    • Object oriented concepts in C#
    • Principles Of Object Oriented Design

提交回复
热议问题