gpt4 book ai didi

c# - 在线设置值

转载 作者:行者123 更新时间:2023-11-30 14:47:12 24 4
gpt4 key购买 nike

我们可以在 C# 中做所有很棒的事情,我想知道我们是否可以做如下的事情:

  string totalWording =
{
if (isA)
return "Value A";

if (isB)
return "Value B";

if (isC)
return "Value C";

return "Default";
};

所以这与 ?: 非常相似,除了你可以有超过 2 个可能的结果

string totalWording = isA ? "Value A" : "Default";

我可以很高兴地创建一个返回值的方法,但我非常喜欢能够立即看到简单的东西

private string GetTotalWording()
{
if (isA)
return "Value A";

if (isB)
return "Value B";

if (isC)
return "Value C";

return "Default";
}

我想听听是否有人有我可以使用的好东西,或者我是否只是靠祈祷生活。

编辑:

还有 func 选项,我想这就是让我进入主题的原因,因为它看起来你应该能够在声明值时直接使用函数......但那可能只是我

    Func<string> getTotalWording = () =>
{
if (isA)
return "Value A";

if (isB)
return "Value B";

if (isC)
return "Value C";

return "Default";
};

最佳答案

使用三元运算符的重复。

string totalWording = isA ? "Value A" : (isB ? "Value B" : (isC ? "Value C" :  "Default"))

还有另一种方法,如果您只有可管理的 if 数量并且它们始终保持不变。创建一个带有字符串值的枚举。

Below answer is based on another on Stack Overflow

您可以为这些带有描述的语句创建一个枚举。

public enum Values
{
[Description("Value A")] A,
[Description("Value B")] B,
[Description("Value C")] C,
[Description("Value D")] D
}

然后,您可以创建一个函数来获取枚举描述

private static string GetEnumDescription(string text)
{
var valueAttribs = typeof(Values).GetMember(text)[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return ((DescriptionAttribute)valueAttribs[0]).Description;
}

然后您可以将它们用作

var variable = "A";

string description =
(Enum.IsDefined(typeof(Values), variable)) ?
GetEnumDescription(variable) : "Default";

Console.WriteLine(description);
Console.ReadLine();

关于c# - 在线设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46424595/

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