Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态字符串。格式取决于参数_C# - Fatal编程技术网

C# 动态字符串。格式取决于参数

C# 动态字符串。格式取决于参数,c#,C#,举例如下: string amountDisplay = presentation.Amount == 1 ? "" : String.Format("{0} x ", presentation.Amount); 是否仍然可以使用String.Format,这样它就可以根据属性进行格式化,而不必对参数的“值”设置条件 另一个用例: String.Format("({0}) {1}-{2}", countryCode, areaCode, phonenumber); 如果我只有电话号码,我会

举例如下:

string amountDisplay = presentation.Amount == 1 ? "" : String.Format("{0} x ", presentation.Amount);
是否仍然可以使用String.Format,这样它就可以根据属性进行格式化,而不必对参数的“值”设置条件

另一个用例:

String.Format("({0}) {1}-{2}", countryCode, areaCode, phonenumber); 
如果我只有电话号码,我会得到像“()-55555”这样的东西,这是不可取的

另一个用例:

String.Format("my {0} has {1} cat[s]", "Aunt", 3) 
在本例中,我希望在[]中包含s,例如,如果值>1

是否存在根据参数值或null删除代码部分的字符串.格式的黑色“语法”


谢谢。

尝试使用条件运算符:

string str = "my {0} has {1} cat" + ((value > 1) ? "s" : "");

str = String.Format(str, "Aunt", value);

仅解决第二个问题,但:

int x = 3;
String.Format("my {0} has {1} cat{2}", "Aunt", x, x > 1 ? "s" : ""); 

不是真的。当然,你可以修改一些复数形式,但它不是一个通用的解决方案来匹配你所有的用例

不管怎样,您都应该检查输入的有效性。如果您希望
areaCode
不为null,并且它是一种可为null的类型,如
string
,请在方法开始时进行一些检查。例如:

public string Foo(string countryCode, string areaCode, string phoneNumber)
{
    if (string.IsNullOrEmpty(countryCode)) throw new ArgumentNullException("countryCode");
    if (string.IsNullOrEmpty(areaCode)) throw new ArgumentNullException("areaCode");
    if (string.IsNullOrEmpty(phoneNumber)) throw new ArgumentNullException("phoneNumber");

    return string.Format(......);
}

用户界面的工作不是补偿用户输入上的一些验证错误。如果数据错误或丢失,请不要继续。这只会给你带来奇怪的错误和很多痛苦。

你也可以尝试多元化服务。大概是这样的:

using System.Data.Entity.Design.PluralizationServices;

string str = "my {0} has {1} {3}";
PluralizationService ps = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us"));
str = String.Format(str, "Aunt", value, (value > 1) ? ps.Pluralize("cat") : "cat");

可能重复的数字上区分正、负和零的can-do条件-@eulerfx您的评论应该是答案。这正是我在这里要问的,如果有办法做到这一点,你会证明自己是完美的。其他的解决方案也可以,但都是黑客,你的解决方案才是我对这个问题的真正答案。请随意将其作为答案发布,以便我可以选择正确的答案。