C# 让用户指定计时器时间?

C# 让用户指定计时器时间?,c#,windows,timer,textbox,dispatcher,C#,Windows,Timer,Textbox,Dispatcher,我希望Dispatcher从文本框中读取时间值:objTextBox。 我尝试了这段代码,但似乎TimeSpan与字符串不兼容,或者我做错了什么 错误:参数1:无法从“字符串”转换为“长” 还有,;在文本框0、0、1或00:00:01中,时间必须是这样吗 代码如下: private void testing() { string theText = objTextBox.Text; DispatcherTimer dispatcherTimer =

我希望Dispatcher从文本框中读取时间值:objTextBox。 我尝试了这段代码,但似乎TimeSpan与字符串不兼容,或者我做错了什么

错误:参数1:无法从“字符串”转换为“长”

还有,;在文本框0、0、1或00:00:01中,时间必须是这样吗

代码如下:

    private void testing()
    {
        string theText = objTextBox.Text;
        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(listjob3_Tick);
        dispatcherTimer.Interval = new TimeSpan(theText);
        dispatcherTimer.Start();
    }

要将字符串转换为时间跨度,请使用
TimeSpan.Parse(str)

我猜您的异常情况如下:

dispatcherTimer.Interval = new TimeSpan(theText);
改用这个:

dispatcherTimer.Interval = new TimeSpan(Convert.ToInt64(theText));

@Snealkybastard:你读过关于构造函数重载的文章吗?您将注意到,它们都不接受字符串参数:整数类型是必需的

阅读后,您可能会发现这些
TimeSpan
方法非常有用:

  • Parse()
  • ParseExact()
  • TryParse()

关于格式,请参见和。如果不同文化的默认时间跨度格式起作用的话,也可以对其进行一些研究。

要从
字符串转换为
时间跨度
,您可以利用,但您必须遵循此格式
[ws][-]{d|[d.]hh:mm[:ss[.ff]]}[ws]
,其中:

ws    is Optional white space.
-     is An optional minus sign, which indicates a negative TimeSpan. 
d     is Days, ranging from 0 to 10675199.
.     is A culture-sensitive symbol that separates days from hours. The invariant format uses a period (".") character.
hh    is Hours, ranging from 0 to 23. 
:     is The culture-sensitive time separator symbol. The invariant format uses a colon (":") character.
mm    is Minutes, ranging from 0 to 59. 
ss    is Optional seconds, ranging from 0 to 59. 
.     is A culture-sensitive symbol that separates seconds from fractions of a second. The invariant format uses a period (".") character.
ff    is Optional fractional seconds, consisting of one to seven decimal digits. 
因此,仅转换天数实际上可以使用
TimeSpan.Parse
并传入字符串-但是如果要转换分钟,则需要对输入进行如下处理:

var input = string.Format("00:{0}", objTextBox.Text.PadLeft(2, '0'));

然后您可以发出
var timeSpan=timeSpan.Parse(输入)因为您已正确格式化它,并且
解析将成功。另一种选择是将分钟变为天,我想,但这需要一些浮点运算,在我看来,这并不是一个好的选择。

我得到了这个错误:System.TimeSpan.Parse(string,System.IFormatProvider)'是一个“方法”,但它的用法与我写的“类型”类似:Dispatchermer.Interval=new TimeSpan.Parse(文本);错误是不言自明的,您不应该在TimeSpan.Parse前面放置新的,因为它是一个静态方法,而不是类型。您能给我一个例子吗?dispatchermer.Interval=TimeSpan.Parse(文本);谢谢你的帮助!:)你如何向用户展示它?例如,选择以小时、分、秒为单位的时间?这将取决于您如何收集计时器的值。一旦决定了,我们就可以给你一些建议。TimeSpan对象构造函数具有TimeSpan(刻度)、TimeSpan(小时、分钟、秒)、TimeSpan(天、小时、分钟、秒)或TimeSpan(天、小时、分钟、秒、毫秒);从我所看到的是滴答声,但我没有看到任何对文本框值的验证。谢谢您的帮助!:)谢谢你的帮助!:)