using class fields from other classes

后端 未结 4 1904
野性不改
野性不改 2021-01-19 04:23

I\'m quite new to C# and OOP so please bear with me.

I have two classes with different namespaces:

namespace Class1

public class class1
{
 public do         


        
4条回答
  •  不思量自难忘°
    2021-01-19 04:53

    You'd probably want to have class2 take in an instance of class1 in its constructor:

    public class class2
    {
     private readonly class1 _c1;
     public class2(class1 c1) { _c1 = c1; }
    
     public double z = _c1.x + 5;
    }
    

    As for how you'd use fields x,y and z with a button click event in a form, you would just access the public fields x, y and z on class1 and class2 instances:

    protected void button_click(){
     class1 c1 = new class1();
     c1.x = 10;
     c1.y = 20;
     class2 c2 = new class2(c1);
    
     //do something with c1 and c2 now...
     Console.WriteLine("{0} {1} {2}", c1.x.ToString(), c1.y.ToString(), c2.z.ToString());
    }
    

    Let me know if I misunderstood what you're looking to do. Hope this helps!

提交回复
热议问题