C#跨类调用方法报错CS1501,矩形计算程序如何修复?
问题修复方案
你的代码存在三个核心问题,直接导致了CS1501错误及后续逻辑问题,逐一修复即可解决:
1. 方法调用未传递必要参数
错误提示明确说明area方法没有接受0个参数的重载——你定义的area(double height, double width)要求必须传入两个double类型参数,但调用时写的a.area()未传参,这是触发错误的直接原因。
2. 静态方法无需实例化对象调用
你定义的area和perimeter是静态方法(static),这类方法属于类本身,不需要创建类的实例(new FormulaMethods()),直接通过类名调用即可。
3. 方法返回值类型错误
你定义的方法返回类型是void(无返回值),但代码里试图把方法调用结果赋值给double类型变量(area = a.area()),这不符合语法规则。需要把方法的返回类型改为double,并在方法内返回计算结果。
修复后的完整代码
using System; namespace RectangleCalculator { public class FormulaMethods { // 修改返回类型为double,并返回计算结果 public static double area(double height, double width) { return height * width; } // 同样修改返回类型和返回逻辑 public static double perimeter(double height, double width) { return 2 * (height + width); } } public class Program { public static void Main(string[] args) { Console.WriteLine("Enter the Height of your rectangle: "); double height = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the Width of your rectangle: "); double width = double.Parse(Console.ReadLine()); Console.WriteLine("The Height of your rectangle is: " + height); Console.WriteLine("The Width of your rectangle is: " + width); // 直接通过类名调用静态方法,传入height和width参数 double area = FormulaMethods.area(height, width); Console.WriteLine("The Area of your rectangle is: " + area); double perimeter = FormulaMethods.perimeter(height, width); Console.WriteLine("The Perimeter of your rectangle is: " + perimeter); } } }
额外优化建议
- 遵循C#命名规范,给方法名首字母大写(比如
Area而非area)。 - 加入输入验证逻辑,用
double.TryParse替代double.Parse,避免用户输入非数字内容导致程序崩溃。
内容的提问来源于stack exchange,提问作者BrittonK
相关产品推荐
相关产品推荐

