如何将 Func<string, string> 传递给采用 Func<object, object> 的函数
How to Pass a Func<string, string> to a function that takes a Func<object, object>
好的,我得到了这个简单的 class
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);
我收到此错误消息
Error CS1503 Argument 1: cannot convert from 'method group' to
'Func<object, object>'
即使我尝试施放 ReadFile
new TFTheOne(args[0]).Bind((Func<object, object>)ReadFile);
有什么解决办法吗?
你不能那样做。考虑这种情况:你的 class 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);
好的,我得到了这个简单的 class
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);
我收到此错误消息
Error CS1503 Argument 1: cannot convert from 'method group' to 'Func<object, object>'
即使我尝试施放 ReadFile
new TFTheOne(args[0]).Bind((Func<object, object>)ReadFile);
有什么解决办法吗?
你不能那样做。考虑这种情况:你的 class 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);