在 C# 中使用 ref [英] Using ref in C#

查看:65
本文介绍了在 C# 中使用 ref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个包含两个类的基本程序.我可以用一个班级来管理:

I am trying to write a basic program, with two classes. I can manage fine with one class:

    public static void Main (string[] args)
    {
        double radius;
        double height;
        double volume;
        {
            System.Console.WriteLine ("Enter radius");
            radius = double.Parse(System.Console.ReadLine());
            System.Console.WriteLine (radius);
            System.Console.WriteLine ("Enter height");
            height = double.Parse(System.Console.ReadLine());
            System.Console.WriteLine (height);

            volume = Math.PI * radius * radius * height;
            System.Console.WriteLine (volume);

但是我无法从一个类到另一个类使用 ref,例如,我尝试删除最终的体积计算并创建这个单独的类:

But I am unable to use ref from one class to another, for example, I tried removing the final volume calculation and making this seperate class:

class Calculation
{
    double radius2 = 0.00;
    double height2 = 0.00;
    double volume2
    radius2(ref radius);
    height2(ref height);
    volume2 = Math.PI * radius2 * radius2 * height2;
}

但它根本不起作用.我是 C# 的新手,感谢您提供的任何帮助!

But it doesn't work at all. I'm quite new to C#, thanks for any help you can offer!

推荐答案

好的.所以.

我将如何编写这个计算类:

How I would write this calculation class:

public class Calculation
{
    public readonly double Result;
    public Calculation(double radius, double height)
    {
        Result = Math.PI * radius * radius * height;
    }
}

然后你会像这样使用它:

Then you would use it like this:

Calculation myCalc = new Calculation(myRadius, myHeight);
double volume = myCalc.Result;

至于ref是什么,看一下关于问题的评论这里.我不擅长解释

As for what ref is, take a look at the comment on the question here. I'm bad with explanations

这篇关于在 C# 中使用 ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆