有了 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";
}
我想听听是否有人有我可以使用的好东西,或者我是否只是靠祈祷生活。
Edit:
还有 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"))
还有另一种方法,如果你只有可控数量的“如果”并且它们始终保持不变。创建一个带有字符串值的枚举。
以下答案基于 Stack Overflow 上的另一个答案 https://stackoverflow.com/a/1799401/7974050
您可以为这些语句创建一个带有描述的枚举。
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)