c# - MyFunction 方法的类型参数(功能) 不能从用法中推断出来
问题描述
我正在尝试下面的这段代码: 有没有办法检查文件是否正在使用? 但是,它给出了错误:无法从用法中推断方法 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);
}
解决方案
您必须有除 Type of 以外的输出void
。
当你这样做时:() => { System.IO.File.etc...; return null; }
输出类型是void
并且你不能拥有一个Func<T>
. 如果你想要一个 Void 类型然后使用Action
.
如果你想要两个void
and T
,那么只需编写一个溢出方法。代码如下:
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);
}
推荐阅读
- json - 快速解析时无法在json post请求参数中添加文本字段输入的文本
- scripting - Dymola mos 脚本:获取当前目录
- javascript - 如何解决父效应子事件的防止事件
- javascript - beforeEach fetch() - 将 res 传递给 'it' 函数
- angular - 使用 Puppeteer SSR for Angular 时闪烁
- python - 当 URL 中没有斜杠时,带有 VueJS 单页的 Django 路由会出现意外行为
- javascript - 如何从导航栏悬停 HTML CSS 中调暗正文?
- arrays - 如何加入每 8 项数组并创建 1 项?
- sql-server - 在 SQL Server 中加载大文本文件
- android - 带有自定义高亮图形的 BottomNavigationBar