从不同的类调用变量c#

时间:2014-10-30 14:47:57

标签: c# .net class oop variables

我正在尝试编写一个包含两个类的程序,并从一个调用另一个变量,但我有两个错误,说'' Area.Circle'不包含'result1的定义'“和” Area.Circle'不包含'result2 '的定义。“我该如何解决这个问题?

using System;

namespace Area
{
    class Circle
    {
        public static void Area()
        {
            Console.WriteLine("Enter the radius of the first circle:   ");
            int r1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the radius of the second circle:   ");
            int r2 = Convert.ToInt32(Console.ReadLine());
            double pi = Math.PI;
            double result1 = pi * r1 * r1;
            double result2 = pi * r2 * r2;
            Console.WriteLine("The area of the first circle is {0}\nThe area of the second circle is {1}\n", result1, result2);
        }
    }

    class Minimum
    {
        static void Main(string[] args)
        {
            Circle.Area();
            Circle one = new Circle();

            double min = Math.Min(Circle.result1, Circle.result2);
            Console.WriteLine("min");

        }
    }
}

3 个答案:

答案 0 :(得分:4)

问题是您要在result1方法的范围内定义result2Area()。在类级别声明它们,public和static,它们将是可访问的。

由于方法Area()是静态的,变量必须也是静态的,以便从中进行访问。您正在从其他类中将变量作为静态访问,因此应该可以正常工作。

答案 1 :(得分:2)

这是因为result1result2Area方法中的局部变量。您必须将它们public类级别(考虑将其转换为Properties):

class Circle
{
    public double Result1 { get; set; }
    public double Result2 { get; set; }
}

需要注意的一点是,如果您将Area声明为static方法,则无法在调用函数中使用实例成员

答案 2 :(得分:0)

当你有一个计算值的方法时,它需要返回它计算给调用者的值。将它们存储在局部变量中并不会将它们暴露给方法的调用者。在这种情况下,由于您要返回两个值,因此您需要将这两个值封装在另一个可以返回的类中。您可以创建自定义类,或者只使用通用类,例如Tuple

public static Tuple<double, double> Area()
{
    Console.WriteLine("Enter the radius of the first circle:   ");
    int r1 = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Enter the radius of the second circle:   ");
    int r2 = Convert.ToInt32(Console.ReadLine());
    double pi = Math.PI;
    double result1 = pi * r1 * r1;
    double result2 = pi * r2 * r2;
    Console.WriteLine("The area of the first circle is {0}\nThe area of the second circle is {1}\n", result1, result2);
    return Tuple.Create(result1, result2);
}

当您致电Area时,您可以将方法的结果存储在变量中,然后再访问该数据。

相关问题