【发布时间】:2020-10-23 10:06:29
【问题描述】:
好的,我有这个简单的类
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:无法从“方法组”转换为 '功能'
即使我尝试投射 ReadFile
new TFTheOne(args[0]).Bind((Func<object, object>)ReadFile);
有没有办法解决这个问题?
【问题讨论】:
-
方法为什么取
Func<object, object>?您的string输入如何映射到object输入,您的object输出如何映射到您的string输出?这似乎是您可能会引入错误的地方。 -
如果 Bind 最终用非字符串的东西调用这个函数会发生什么?
-
一个简单的桥梁类似于
.Bind(o => ReadFile(o as string)),但您确实需要(对自己)回答我在第一条评论中提出的问题。 -
你的课可能很简单,但它很复杂,你的意图也不清楚。这似乎是某种 Fluent Api。然而,你真正想要实现的是什么?
-
@TheGeneral 编码作业作为对 Monads 的介绍。 C# 绝对不是我的首选,但我现在有点坚持。