【问题标题】:Returning a nested class from inherited class从继承的类返回嵌套类
【发布时间】:2018-08-08 08:30:27
【问题描述】:

刚接触 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中编写坐标(返回纬度和经度)、天气(返回摘要、描述、可见性)的返回函数。

请帮忙。谢谢!

【问题讨论】:

  • 你好。不确定您的问题是什么?请您进一步解释一下。我可以看到你的课程设计,但你不能做什么或有什么问题?
  • 我想在weatherAPI里面写一个函数,可以返回继承的类(egs坐标)。我将在某处创建一个weatherAPI对象并调用指定的坐标函数,返回坐标值(即经度和纬度)。
  • 您将嵌套类称为parent.nestedclass。所以一般来说就像public weatherData.coordinates GetGoordinate()。但是在这种情况下,由于嵌套类在您声明方法的类内部,您可以只使用public coordinates GetGoordinate()。已经说过嵌套类很少是您想要的良好设计。我会把它们都作为单独的类。

标签: c# class object inheritance nested


【解决方案1】:

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

您正在寻找组合,使用属性。当您使用它时,请遵守 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2014-03-01
    相关资源
    最近更新 更多