方法 MyFunction<T>(Func) 的类型参数<T>无法从用法中推断出来



我正在尝试下面这段代码:是否有一种方法来检查文件是否正在使用?但是,它给出了错误:TimeoutFileAction(Func)方法的类型参数不能从用法中推断出来。

你知道怎么解决这个问题吗?

TimeoutFileAction(() => { System.IO.File.etc...; return null; } );
Reusable method that times out after 2 seconds
private T TimeoutFileAction<T>(Func<T> func)
{
var started = DateTime.UtcNow;
while ((DateTime.UtcNow - started).TotalMilliseconds < 2000)
{
try
{
return func();                    
}
catch (System.IO.IOException exception)
{
//ignore, or log somewhere if you want to
}
}
return default(T);
}

你必须有一个非void类型的输出

当你这样做时:() => { System.IO.File.etc...; return null; }输出类型是void,你不能有Func<T>。如果你想要一个Void类型,那么使用Action

如果同时需要voidT,那么只需编写一个溢出方法。代码:

public static void Main()
{
var today = new DateTime(2021, 10, 25, 5, 40, 0);
Console.WriteLine(today.AddHours(7).AddMinutes(36));
TimeoutFileAction(() => { Test(); });
TimeoutFileAction(Test);
}
private static string Test() => "Test";
private static void TimeoutFileAction(Action func)
{
var started = DateTime.UtcNow;
while ((DateTime.UtcNow - started).TotalMilliseconds < 2000)
{
try
{
func();
}
catch (IOException exception)
{
//ignore, or log somewhere if you want to
}
}
}
private static T TimeoutFileAction<T>(Func<T> func)
{
var started = DateTime.UtcNow;
while ((DateTime.UtcNow - started).TotalMilliseconds < 2000)
{
try
{
return func();
}
catch (IOException exception)
{
//ignore, or log somewhere if you want to
}
}
return default(T);
}