Public Sub Delay(ByRef HowLong As Double)
On Error Resume Next
Dim throughTime As DateTime
Dim Dnow As DateTime = DateTime.Now
'throughTime = DateAdd(DateInterval.Second, HowLong, Now)
throughTime = Dnow.AddSeconds(HowLong)
Do While throughTime > DateTime.Now
Application.DoEvents()
Loop
End Sub
转写为C#如下,却出现了问题:
public void Delay(ref double HowLong)
{
DateTime throughTime;
DateTime Dnow = DateTime.Now;
throughTime = Dnow.AddSeconds(HowLong);
while (throughTime > DateTime.Now)
{
Application.DoEvents();
}
}
错误1
与“Delay(ref double HowLong)”最匹配的重载方法具有一些无效参数
错误2
参数“1“无法从”int"转换为"ref double"
请教大家。我对C#不太懂,请问要如何修改?
public void Delay(double HowLong) 就好,不需要用 ref
胡国宏的看法:
错误1
与“Delay(ref double HowLong)”最匹配的重载方法具有一些无效参数
错误2
参数“1“无法从”int"转换为"ref double"
上面的两个错误其实是一个错误,因为你的调用写的是:
Delay(20)
而编译器将20解释为int类型,运行时自然会去查找
Delay(int HowLong)函数,而你仅仅定义了
Delay(ref double HowLong)函数
当无法将 int 类型隐式转换为ref double就会出现上面的错误。
vb之所以没有出错,是因为编译器选项默认设置是: option strict == off
正确的作法是按下面的方式调用:
Delay((double)20);
Delay((double)20);
我测试了一下,编译有误。
我分析原因是:编译器将参数(double)20解释为右值(rvalue),
而ref定义的参数必须是左值,lvalue。所以出错。
另外一个原因是double类型无法隐式转换为ref double.
可以采用以下方法:
方法一、如8620(tuenhai)所说,更改public void Delay(ref double HowLong),
定义为public void Delay(double HowLong)
方法二、不更改定义,更改调用方式
double HowLong = 20;
this.Delay(ref HowLong );
public void Delay(int m)
{
DateTime endTime = DateTime.Now.AddMilliseconds((double)m);
while (endTime > DateTime.Now)
{
Application.DoEvents();
}
}