简体   繁体   中英

C# console, How to reach the identified variable from one class to another class?

    interface ICar
    {
        int Speed {get; set;}
    }
    class IgnitionKey: ICar
    {
        public int Speed {get; set;}
        public void Change () 
        {
            Speed = 10;
        }
    }

    class GasBrake: IgnitionKey
    {

    }
    static void Main(string[] args)
    {
        IgnitionKey k = new IgnitionKey();
        GasBrake s = new GasBrake();
        k.Change();
        Console.WriteLine(s.Speed);
        Console.ReadLine();
    }

Here is my code. Using Change function, I change speed value to 10. But this speed value belongs to interface (I guess). I have a second class that inherits from other class. I want Speed value to be equal to ten.

In main, if I use Console.WriteLine(k.Speed) I can get value 10. But I need to get this value when I use s.Speed. How can I do that ? Is there a way to change the value of first class using second class ?

(Sory for bad English)

In your code, k and s refer do different objects, so changes in one of them cannot affect the other. You can write GasBrake s = k; to make booth variables refer to the same object, or you may call s.Change() instead of k.Change() to modify s

When you do :

 GasBrake s = new GasBrake();

or:

IgnitionKey k = new IgnitionKey();

that is a new object created and it has it's own allocated memory and it's own state which is completely isolated from the other and they don't have any shared state.

As you have two completely different objects being created they both will have completely different state, they cannot share state. For mimicking what you want you will need to use single object but with different type of reference :

GasBrake s = new GasBrake(); // now just one object created
IgnitionKey k = s;  // we reference to it using the parent class type 
k.Change();  // change it's value

    Console.WriteLine(s.Speed); // same value will be printed

now you will see same value ie 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM