首页 > 解决方案 > 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);
}

标签: c#

解决方案


您必须有除 Type of 以外的输出void

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

如果你想要两个voidand 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);
    }

推荐阅读