You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#方法参数调用疑问及代码报错解决:如何跨类调用参数计算

问题解答:实例参数跨类计算展示 + 代码错误排查

我来帮你一步步解决这两个问题——先搞定代码里的报错,再讲怎么在其他类里用实例的内部参数做计算展示。

一、你的C#代码错误分析与修正

先看这段代码的核心问题:

  • 方法参数完全多余且命名冲突:Area和Perimeter方法里的参数根本没必要,因为width和height是Box类的成员字段,方法内部直接就能调用。而且参数名和方法名重名(比如Area方法的参数叫Area),这会让编译器混淆,也不符合编码规范。
  • 调用方法时传递了未定义的变量:Main里的b.Area(Area);和b.Perimeter(Para);中,Area和Para根本没在Main方法里定义过,编译器不知道这俩是什么,自然会报错。

修正后的可运行代码:

using System;

class Box {
    // 先把字段设为public,后面会讲更规范的封装方式
    public int width = 10;
    public int height = 15;
    
    // 移除多余参数,直接用类内部字段计算返回
    public int Area() {
        return width * height;
    }
    
    public int Perimeter() {
        return 2 * (height + width);
    }
}

class Program {
    static void Main(string[] args) {
        Box b = new Box();
        // 调用方法接收结果,然后输出展示
        int areaResult = b.Area();
        int perimeterResult = b.Perimeter();
        Console.WriteLine($"盒子面积:{areaResult}");
        Console.WriteLine($"盒子周长:{perimeterResult}");
        Console.ReadLine();
    }
}

二、在其他类中访问实例内部参数并计算展示的方法

要在其他类里用Box实例的内部参数(比如width、height)做计算,通常有三种常用方式,各有优缺点:

1. 直接把字段设为public(简单直接,适合小型项目)

就像上面修正的代码那样,把width和height设为public,其他类就能直接访问实例的这些字段来实现自定义计算:

// 新增一个专门做计算的类
class BoxCalculator {
    public static void ShowCustomArea(Box box) {
        // 这里可以写任意自定义计算逻辑,比如计算两倍面积
        int doubleArea = box.width * box.height * 2;
        Console.WriteLine($"盒子的两倍面积:{doubleArea}");
    }
}

// 在Main里调用这个类的方法:
Box b = new Box();
BoxCalculator.ShowCustomArea(b);

2. 用属性封装字段(封装性更好,推荐生产环境使用)

如果不想把字段直接暴露给外部(防止被随意修改),可以用只读属性来封装,外部只能获取值不能修改:

class Box {
    // 私有字段,只有类内部能修改
    private int width = 10;
    private int height = 15;
    
    // 只读属性,外部只能读取
    public int Width => width;
    public int Height => height;
    
    // 原有方法保留
    public int Area() {
        return width * height;
    }
}

// 其他类通过属性访问字段:
class BoxCalculator {
    public static void ShowHalfPerimeter(Box box) {
        double halfPeri = (box.Height + box.Width);
        Console.WriteLine($"盒子的半周长:{halfPeri}");
    }
}

3. 通过方法传递参数(完全隔离内部实现,最安全)

如果想彻底隐藏Box的内部字段,也可以在调用其他类方法时,把需要的参数单独传进去:

class Box {
    private int width = 10;
    private int height = 15;
    
    // 提供获取字段的方法
    public int GetWidth() {
        return width;
    }
    
    public int GetHeight() {
        return height;
    }
}

class BoxCalculator {
    // 直接接收需要的参数做计算
    public static int CalculateArea(int width, int height) {
        return width * height;
    }
}

// 在Main里调用:
Box b = new Box();
int area = BoxCalculator.CalculateArea(b.GetWidth(), b.GetHeight());
Console.WriteLine($"计算得到的面积:{area}");

内容的提问来源于stack exchange,提问作者Toy99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:03:50