我正在阅读XML Weather文档,其格式如下 -
<Rep D="ENE" F="1" G="9" H="81" Pp="9" S="7" T="3" V="VG" W="7" U="0">0</Rep> // 00:00
<Rep D="NE" F="0" G="9" H="86" Pp="1" S="4" T="3" V="VG" W="2" U="0">180</Rep> //03:00
<Rep D="NNE" F="0" G="9" H="87" Pp="4" S="4" T="2" V="GO" W="7" U="0">360</Rep> //06:00
<Rep D="NNE" F="2" G="7" H="81" Pp="8" S="4" T="4" V="VG" W="7" U="1">540</Rep> //09:00
<Rep D="NNE" F="5" G="7" H="72" Pp="4" S="2" T="6" V="VG" W="7" U="2">720</Rep> //12:00
<Rep D="N" F="6" G="7" H="69" Pp="4" S="2" T="7" V="VG" W="7" U="1">900</Rep> //15:00
<Rep D="NW" F="5" G="4" H="77" Pp="5" S="2" T="6" V="VG" W="7" U="1">1080</Rep> //18:00
<Rep D="N" F="2" G="9" H="88" Pp="8" S="4" T="4" V="VG" W="8" U="0">1260</Rep> //21:00
Rep元素的文本值与以分钟为单位的时间相关。
为了确保我正在使用if语句读取正确的元素我将Rep元素的innerText存储为变量然后计算出已经有多少分钟并将此值与innerText进行比较以查看我应该使用哪一行阅读
string RepValueZero = elemList[0].InnerText;
string RepValueZero = elemList[0].InnerText;
//Get the Number of Minutes in the day to calculate which row to read
double mins = DateTime.Now.TimeOfDay.TotalMinutes;
if (mins > Convert.ToInt32(RepValueZero) && mins < Convert.ToInt32(RepValueOne))
{
//Get Temp and Weather Value From Row [0]
string strTemp = elemList[0].Attributes["T"].Value;
string strWeatherType = elemList[0].Attributes["W"].Value;
}
......等等。
获得&#39; W&#39;的价值。 - 我想要显示图像的天气类型。 (但是&#39; W&#39;)有30个可能的值。如果没有在每个初始if语句中有30个分支的嵌套if语句,我怎样才能实现这个目标
if(W = 1)
{
image1.ImageUrl = "w1.jpg";
}
if(W = 2)
{
image1.ImageUrl = "w2.jpg";
}
...
...
if(W = 30)
{
image1.ImageUrl = "w3.jpg";
}
如下所示
string RepValueZero = elemList[0].InnerText;
string RepValueZero = elemList[0].InnerText;
//Get the Number of Minutes in the day to calculate which row to read
double mins = DateTime.Now.TimeOfDay.TotalMinutes;
if (mins > Convert.ToInt32(RepValueZero) && mins < Convert.ToInt32(RepValueOne))
{
//Get Temp and Weather Value From Row [0]
string T = elemList[0].Attributes["T"].Value;
string W = elemList[0].Attributes["W"].Value;
if(W = 1)
{
image1.ImageUrl = "w1.jpg";
}
if(W = 2)
{
image1.ImageUrl = "w2.jpg";
}
...
...
if(W = 30)
{
image1.ImageUrl = "w3.jpg";
}
}
答案 0 :(得分:1)
您可以替换它:
if(W = 1)
{
image1.ImageUrl = "w1.jpg";
}
if(W = 2)
{
image1.ImageUrl = "w2.jpg";
}
...
用这个:
image1.ImageUrl = "w" + W + ".jpg";
或者,如果每个数字都有不同的图像,则可以执行以下操作:
Dictionary<int, string> jpgsById = new Dictionary<int, string> ();
jpgsById[1] = "w1.jpg";
jpgsById[2] = "w2.jpg";
image1.ImageUrl = jpgsById[1];
答案 1 :(得分:1)
您可以创建30个继承自Weather类的类,并具有WeatherFactory模式,该模式根据字符串参数返回特定的WeatherSubclass。
abstract class Weather
{
public string ImageUrl{get;set;};
}
class MildWeather : Weather
{
public MildWeather()
{
ImageUrl = "your specific image for MildWeather";
}
}
并在您的代码中包含类似这样的内容
string T = elemList[0].Attributes["T"].Value;
string W = elemList[0].Attributes["W"].Value;
var weather = WeatherFactory.Create(W);
image1.ImageUrl = weather.ImageUrl;
因此,如果您想要添加另一个子类,因为在您的xml中出现另一个W值,您需要做的是从Weather类继承并指定该类型的图像,并且您的模型对于这些更改是可扩展的。您不需要添加额外的if。