繁体   English   中英

在C#上使用串联

[英]using concatenation on c#

连接这些元素的正确方法是什么?

环境:C#-WinForm-Desktop。

在我的应用程序中,我有一个名为config.ini的文本文件。 此文件的值具有以下术语:

csv_month_hour =值

因此,数据为:

[csv]
csv_01_01=value // 24 hours a day in January
csv_01_02=value 
csv_01_03=value 
.
csv_02_01=value // 24 hours a day in February
csv_02_02=value 
csv_02_03=value 
.
// and so on

我的应用程序具有以下方法:

private void getMonthHour()
{
    DateTime Xdt = DateTime.Now;
    int Xmonth = Xdt.Month;
    int Xhour = Xdt.Hour;

    if (File.Exists("config.ini"))
    {
        IniFile ini = new IniFile("config.ini");

        m3h = Convert.ToDouble(confg.csv["csv_" + Xmonth.ToString + "_" + Xhour.ToString]);
    }
}

timer_ticktimer_tick调用一次此方法,以检查月份和时间以使用相应的值。

我需要知道如何将其连接:m3h = Convert.ToDouble(confg.csv [“ csv _” + Xmonth.ToString +“ _” + Xhour.ToString]);

该代码的示例为:

if (Xmonth==1&&Xhour==1){m3h = Convert.ToDouble(confg.csv.csv_01_01);}
else if (Xmonth==1&&Xhour==2){m3h = Convert.ToDouble(confg.csv.csv_01_02);}  
else if (Xmonth==1&&Xhour==3){m3h = Convert.ToDouble(confg.csv.csv_01_03);}
// csv_month_hour in this case 01 is January.
else if (Xmonth==2&&Xhour==1){m3h = Convert.ToDouble(confg.csv.csv_02_01);}
// And so on, until December (12).   

从代码中的方法调用中排除无效的语法/编译器错误,我怀疑您正在构建字符串,但无法在数字0-9前面获得前导0 因此,当XmonthXhour小于10时,您的字符串将构建为"csv_1_1"而不是预期的"csv_01_01"

要指示ToString方法在需要时包括前导零,可以提供自定义数字格式字符串 "00" (请参见链接中的“零占位符”的第一个条目)。

尝试使用Xmonth.ToString("00")Xhour.ToString("00")

Monitor.malyt.m3h = Convert.ToDouble(confg.csv["csv_" + 
    Xmonth.ToString("00") + "_" + 
    Xhour.ToString("00")]);

这将在需要时输出XmonthXhour的值,并带有一个前导零。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM