0

我有一个包含几个类的 API。在一个类中,我想使用其他类的变量。我该怎么做呢?

谢谢!

public class Rain
{
    public decimal rainValueInCM;
    public decimal rainValueInMM;
   // public Dictionary<decimal, Temperature> Temperature = new Dictionary<decimal, Temperature>();

    public Rain(decimal cm)
    {
        rainValueInCM = cm;
    }

    public  decimal ConvertToCM(decimal mm)
    {   
        rainValueInCM = (mm / 10);
        return rainValueInCM;  
    }

例如,在另一个类中,我想使用该类中的变量“rainValueInCM”。

4

2 回答 2

3

Simply you have to create an instance of the class Rain and access it values this way:

public class Rain
{
    public decimal rainValueInCM;
    public decimal rainValueInMM;
   // public Dictionary<decimal, Temperature> Temperature = new Dictionary<decimal, Temperature>();

    public Rain(decimal cm)
    {
        rainValueInCM = cm;
    }

    public  decimal ConvertToCM(decimal mm)
    {   
        rainValueInCM = (mm / 10);
        return rainValueInCM;  
    }
}

public class AnotherClass
{
     public void SomeMethod() 
     {
         Rain myRain = new Rain(5); // create the instance
         // use the value
         decimal theValue = myRain.rainValueInCM;
     }
}

Anyway I recommend you to read about C# properties, since there isn't a good practice to expose as public your class value members. Gook luck!

于 2013-04-16T00:25:49.380 回答
0

First you need a getter and setter for the property

public class Rain
{
    public decimal rainValueInCM { get; set; }
    ...
}

Then instantiate an object of type Rain in the other class and get the property

public class MyOtherClass
{
    public void MyMethod() {
         Rain rain = new Rain();
         decimal cm = rain.rainValueInCM;
    }

}
于 2013-04-16T00:25:43.257 回答