你不使用类字段(除非它们是静态的,但在你的情况下它们不是),但是对象字段。这里有一个如何实现你想要的例子。
public class1 {
public double Radius;
// Function to calculate the area
public double Area(double Rad) {
this.Radius = Rad;
return Math.PI * Math.Pow(this.Radius, 2);
}
}
public class2 {
public double Depth;
// Function to calculate the volume of a cylinder
public double Volume(double Rad, double Dep) {
this.Depth = Dep;
// Create an instance of Class1 and use it to calculate the Volume
var Obj1 = new class1();
return Obj1.Area(Rad) * this.Depth;
}
}
如何使用上面的按钮单击事件
// Let's calculate an Area from a Radius
double SomeRadius = 1.234;
MyObj1 = new class1();
double Area = MyObj1.Area(SomeRadius);
double StoredRadius = MyObj1.Radius; // This will give you back the Radius stored by MyObj1, which is the same you passed to Area() function
// Now let's calculate a Volume, using the Radius we indicated earlier and a Depth
double SomeDepth = 4.567;
MyObj2 = new class2();
double Volume = MyObj2.Volume(SomeRadius, SomeDepth);
double StoredDepth = MyObj2.Depth; // This will give you back the Depth stored by MyObj2, which is the same you passed to Volume() function
稍后退后一步,定义您的类实际表示的内容。他们不只是变量的桶。 'class1'和'class2'自然没有任何意义。你试图完成的任务可能以任何方式完成,但是“OOP新手”我们应该专注于确定正确的方式。那么,除了一个人为的例子之外,你们的课堂所代表的物理或概念对象是什么? – David 2012-08-07 01:07:45
我有两个类,class1中的变量需要在class2中使用。例如,area = PI * r^2是class1中的一种方法。 Volume = area * depth是class2中的一种方法。此外,我有一个表格,其中将会计算面积和体积。我试图解决的是如何在class1和class2中使用r,然后在按钮事件中使用这些变量。我希望这更清楚。谢谢你的初始回复。 – user1580591 2012-08-07 01:14:46
我在澄清后更新了我的答案,希望它有帮助。 :) – Diego 2012-08-07 01:37:48