简体   繁体   English

如何索引字符串数组

[英]How to index a string array

I have a string array in C# 3.5: 我在C#3.5中有一个字符串数组:

string [] times = new[] {“08:00 am” , “10:00 am”, “120”} ; 

I would like to create indexes to times: StartTime , EndTime , ElapsedTime so that when I code: 我想创建时间索引: StartTimeEndTimeElapsedTime以便在我编写代码时:

StartTime= “09:00 am” ; 
EndTime= “11:00 am” ; 

then times[0] is set to “09:00 am” , etc. 然后将times[0]设置为“09:00 am”“09:00 am”

I could create 3 methods: 我可以创建3种方法:

private void StartTime(string time)
{    times[0] = time;  }
private void EndTime(string time)
{    times[1] = time;  }
private void ElapsedTime(string time)
{    times[2] = time;   }

and code 和代码

StartTime("09:00");  

but is there a simpler way to do it? 但是有更简单的方法吗?

What you should really do is create a new class to do this. 您真正应该做的是创建一个新类来执行此操作。 Make the two times properties. 设置两次属性。

And the time elapsed is a function of the start and end times. 并且经过的时间是开始时间和结束时间的函数。

class Time 
{
    public DateTime StartTime{ get; set; }
    public DateTime EndTime{ get; set; }

    public String[] ToStringArray() 
    {
        String[] ret = new String[3];
        ret[0] = StartTime.ToString();
        ret[1] = EndTime.ToString();
        ret[2] = ElapsedTime().ToString();
        return ret;
    }

    public TimeSpan ElapsedTime() 
    {
        return EndTime.subtract(StartTime);
    }
}

I don't know it it is simpler, but I would suggest taking the hard index references out of your code and replace them with constants, to make easier to maintain if the order of elements in the array would change in the future: 我不知道它更简单,但是我建议从代码中删除硬索引引用,并用常量替换它们,以使将来如果数组中元素的顺序发生变化时可以更容易维护:

private const int START_TIME = 0;
private const int END_TIME = 1;
private const int ELAPSED_TIME = 2;

Then you will also get more readable code: 然后,您还将获得更具可读性的代码:

times[END_TIME] = time;

Unless you want to be more object oriented, in which case you should follow jjnguy's advice. 除非您希望更加面向对象,否则应遵循jjnguy的建议。

要添加到jjnguy的答案中,您确实应该有一个包含3个属性的类,然后,如果需要一个数组,则可以有一个公共属性,该属性只有一个getter并在字符串数组中返回3个不同的时间。

Use a dictionary. 使用字典。 See here . 这里

How about an extension method? 扩展方法怎么样?

public static class Extensions
{
   public static void StartTime(this string[] array, string value)
   {
      array[0] = value;
   }
}

You can do this using a dictionary. 您可以使用字典来做到这一点。

eg 例如

Dictionary<string, string> times = new Dictionary<string, string>();
times.Add("StartTime","09:00am");
times.Add("EndTime","11:00am");

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

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