如何将Func <string,string>传递给采用Func <object,object>的函数

问题描述

好,所以我有这个简单的课程

    private class TFTheOne
    {
        private object value;

        public TFTheOne(object value)
        {
            this.value = value;
        }

        public TFTheOne Bind(Func<object,object> func)
        {
            value = func(value);
            return this;
        }

        public void PrintMe()
        {
            Console.WriteLine(value);
        }
    }

功能

    public static string ReadFile(string filePath)
    {
        return File.ReadAllText(filePath);
    }

现在,当我尝试将ReadFile传递给TFTheOne.Bind函数

 new TFTheOne(args[0]).Bind(ReadFile);

我收到此错误消息

错误CS1503参数1:无法从“方法组”转换为 'Func '

即使我尝试投射ReadFile

new TFTheOne(args[0]).Bind((Func<object,object>)ReadFile);

有什么办法解决吗?

解决方法

您不能那样做。考虑这种情况:类TFTheOne拥有一个整数值,如果允许这样做,则函数调用时会崩溃,因为它期望一个字符串。

您可以做的是创建一个包围Func<string,string>()的lambda,并检查传递给它的参数是否真的是字符串:

.Bind((o) => o is string ? ReadFile((string)o) : null);
,

Func<T,TResult>相对于T相反,因此只能使用较少特定类型的输入。

对于您而言,您需要包装ReadFile方法以确保它可以与任何object一起使用。

根据您的要求,类似的事情会起作用:

new TFTheOne(args[0]).Bind(o => ReadFile(o?.ToString()));

尽管“更好”的设计将使Bind重载:

public TFTheOne Bind(Func<string,object> func)
{
    value = func(value);
    return this;
}

现在,由于TResult协变变量,因此可以正常编译:

new TFTheOne(args[0]).Bind(ReadFile);