从继承的类返回嵌套类

时间:2018-08-08 08:30:27

标签: c# class object inheritance nested

c#的新手,并在构建天气API时尝试遵循特定的代码结构

  public class weatherData
   {
    public class coordinates
    {
        protected string longitude;   //coord.lon for opw
        protected string latitude;    //coord.lat for opw
    }

    public class weather
    {
        protected string summary;     //weather.main for opw
        protected string description;
        protected double visibility;  // only for  DS
    } }

    public class weatherAPI : weatherData
{


}

我正在尝试为weatherAPI中的坐标(返回纬度和经度),天气(返回摘要,描述,可见性)编写一个返回函数。

请帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

您不是在寻找嵌套类或继承。两者都有他们的位置,但是那不在这里。参见:

您正在使用属性寻找合成。同时,请遵守C#命名约定并在可能的情况下使用属性:

public class Coordinates
{
    public string Longitude { get; set; }   //coord.lon for opw
    public string Latitude { get; set; }    //coord.lat for opw
}

public class Weather
{
    public string Summary { get; set; }     //weather.main for opw
    public string Description { get; set; }
    public double Visibility { get; set; }  // only for  DS
} 

// A composed class 
public class WeatherData
{
    public Coordinates Coordinates { get; set; }
    public Weather Weather { get; set; }
}

现在您可以编写方法了:

public class WeatherAPI
{
    public WeatherData GetWeatherData()
    {
        var data = new WeatherData();
        data.Coordinates = new Coordinates
        {
            Longitude = ...,
        };
        data.Weather = new Weather
        {
            Summary = ...,
        };

        return data;
    }
}