gpt4 book ai didi

c# - 作为方法调用参数的函数

转载 作者:太空狗 更新时间:2023-10-30 00:39:25 26 4
gpt4 key购买 nike

我有一个可能很容易回答的简单问题,但大量使用谷歌并没有找到我问题的答案。因此,如果有正确的解决方案但我没有看到,我深表歉意。

如果我有这样的方法调用

Object.Add(string text, System.Drawing.Color color);

那是用指定的颜色向某个对象添加一些文本,我想动态改变颜色,然后我可以输入某事。喜欢

Object.Add("I'm a string", SomeBool ? Color.Red : Color.Green);

这非常有用,但一旦我想比较两个以上的案例时就会失败。

我正在寻找的是(伪代码)之类的东西

Object.Add("I'm another string", new delegate (Sytem.Drawing.Color) 
{
if (tristate == state.state1)
{
return Color.Blue;
}
else if (tristate == state2)
{
return Color.Green;
}
// ...
});

但无论我尝试什么,它都会抛出一个编译器错误。

我尝试了很多关于如何将函数作为方法参数传递的谷歌搜索,但我发现的很像

public void SomeFunction(Func<string, int> somefunction) 
{
//...
}

这不是我的问题。

谢谢你:)

最佳答案

只要把你的逻辑放在第一位:

Color color;

if (tristate == state1)
color = Color.Blue;
else if (tristate == state2)
color = Color.Green;
else
color = Color.Red;

Object.Add("I'm a string", color);

您的 delegate 解决方案不起作用的原因很简单,new delegate (Sytem.Drawing.Color) { … } 返回一个需要首先调用的函数委托(delegate)在获得颜色值之前。并且由于您的方法需要一种颜色而不是返回颜色的方法,因此它并不是很有帮助。

根据您的逻辑有多短,您仍然可以在此处使用三元条件运算符并简单地链接它:

Object.Add("I'm a string", tristate == state1 ? Color.Blue : tristate == state2 ? Color.Green : Color.Red);

这相当于上面冗长的 if/else if/else 结构。但当然,它不一定更具可读性,因此请谨慎使用并选择更具可读性的解决方案。

关于c# - 作为方法调用参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35649530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com