【发布时间】:2018-08-23 23:25:45
【问题描述】:
C# 我搜索了但找不到我自己所处的具体情况。如何从另一个类调用一个类中的方法?
public class Box
{
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
public double Volume(double len, double bre, double hei)
{
double totvolume;
totvolume = len * bre * hei;
return totvolume;
}
}
public class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); //create new class called Box1
Box Box2 = new Box(); //create new class called Box2
double returnvolume; //create variable to hold the returned data from method
// box 1 specification
Box1.length = 6.0;
Box1.breadth = 7.0;
Box1.height = 5.0;
// box 2 specification
Box2.length = 11.0;
Box2.breadth = 16.0;
Box2.height = 12.0;
//Calculate and display volume of Box1
Box.Volume volumebox1 = new Box.Volume(); //creating new instance of Volume method called volumebox1
returnvolume = volumebox1.Volume(Box1.length, Box1.breadth, Box1.height); //giving variables to method
Console.WriteLine("Volume of Box1 : {0}", volumebox1); //write return value
//Calculate and display volume of Box2
Box.Volume volumebox2 = new Box.Volume(); //creating new instance of Volume method called volumebox2
returnvolume = volumebox2.Volume(Box2.length, Box2.breadth, Box2.height); //giving variables to method
Console.WriteLine("Volume of Box1 : {0}", volumebox2); //write return value
Console.ReadKey();
}
这给出了错误“类型名称'Volume'不存在于类型'Box'中
【问题讨论】:
-
您是否尝试将
Box.Volume volumebox1 = new Box.Volume(); //creating new instance of Volume method called volumebox1 returnvolume = volumebox1.Volume(Box1.length, Box1.breadth, Box1.height);更改为:var returnvolume = Box1.Volume(Box1.length, Box1.breadth, Box1.height);?
标签: c# class methods types typename