使用从其他类类字段 [英] using class fields from other classes
问题描述
我很新的C#和面向对象的,所以请多多包涵。
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 double x;
public double y;
}
...
namespace Class2
public class class2
{
public double z = x + 5;
}
我创建了一个项目,称为添加和有一个按钮的形式。该按钮将增加的x,y和z。我的问题是:
I have created a project called add and have a form with a button. The button will add x, y and z. My questions are:
我如何使用Class2中域x以及如何使用领域的x,y和z下按钮单击事件?
How do I use field x in class2 and how do I use fields x, y and z under button click event?
推荐答案
您很可能希望有类2
取一个实例的 1级
在其构造:
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;
}
至于你会如何使用领域的x,y和z的一个按钮单击窗体中的事件,你只需进入公共领域的X,Y和1级和Class2中的实例Z:
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!
这篇关于使用从其他类类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!