作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我有我的代码的简单示例,但我找不到如何重写它的想法。代码:
class Program
{
static void Main(string[] args)
{
var cat = new Cat();
cat
.ToFeed(arg => LikeMilk(1), c => c.Inc())
.ToFeed(arg => LikeMilk(2), c => c.Inc());
}
private static bool LikeMilk(int liters)
{
return liters <1;
}
}
public class Cat
{
private int Weith { get; set; }
public void Inc()
{
Weith++;
}
public Cat ToFeed(Func<int, bool> predicate, Action<Cat> action)
{
if (predicate) // Error: Cannot implicitly convert type 'System.Func<int,bool>' to 'bool'
action(this);
return this;
}
}
}
我当然可以更改签名ToFeed
至 ToFeed(bool predicate, Action<Cat> action),
但我不想这样做。我知道我必须将 int 参数添加到谓词调用中,但我已将其添加到 Main()
中
我该如何解决这个问题?
谢谢
最佳答案
我相信你的方法应该是这样的:
public Cat ToFeed(Func<int, bool> predicate, Action<Cat> action)
{
if (predicate(Weith)) // By the way, it is properly the word Weight you're looking for :)
action(this);
return this;
}
predicate(Weith)
执行函数 predicate
与属性(property)的值(value) Weith
. Func<int, bool>
本身不是 bool(true/false - 这是 if 语句所期望的。)但是,它是你可以执行的东西,以 int 作为参数,以获得 bool,因此你需要 (arguments)
.
更新:
我不完全确定你想要什么。但是你可以按照你自己说的去做,使用 bool
而不是 Func<*>
.而如果你希望你对 LikeMilk 的评价被延迟,你可以这样说:
public Cat ToFeed(Func<bool> predicate, Action<Cat> action)
{
if (predicate())
action(this);
return this;
}
和
var cat = new Cat().ToFeed(() => LikeMilk(1), c => c.Inc())
.ToFeed(() => LikeMilk(2), c => c.Inc());
但这没有多大意义,因为您的方法 LikeMilk
将返回相同的东西是否延迟执行。
关于c# - Func 和不能隐式转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095121/
我是一名优秀的程序员,十分优秀!