简体   繁体   English

动态String.Format取决于params

[英]dynamic String.Format depending of params

Giving the following examples: 给出以下示例:

string amountDisplay = presentation.Amount == 1 ? "" : String.Format("{0} x ", presentation.Amount);

is there anyway to use String.Format so it formats depending on properties without having to do a condition of the 'value' of the parameters ? 无论如何使用String.Format所以它的格式取决于属性,而不必做参数的'值'的条件?

another use case: 另一个用例:

String.Format("({0}) {1}-{2}", countryCode, areaCode, phonenumber); 

if I only have phonenumber, I would end up with something like "() -5555555" which is not desirable. 如果我只有phonenumber,我最终会得到类似“()-5555555”的东西,这是不可取的。

another use case : 另一个用例:

String.Format("my {0} has {1} cat[s]", "Aunt", 3) 

in this case, I would like to include the s in the [] if the value > 1 for example. 在这种情况下,如果值> 1,我想在[]中包含s。

Is there any black 'syntax' of String.Format that removes code parts depending on value of parameters or null ? 是否有任何String.Format的黑色'语法'根据参数值删除代码部分或null?

Thanks. 谢谢。

Not really. 并不是的。 You can hack some things for the plural [s], sure, but it won't be a generic solution to match all your use cases. 你可以为复数[s]破解一些东西,当然,但它不是一个匹配所有用例的通用解决方案。

You should check the validity of your input regardless. 无论如何,您都应该检查输入的有效性。 If you're expecting areaCode to be not null, and it's a nullable type like string , do some checks at the start of your method. 如果您希望areaCode不为null,并且它是像string一样的可空类型,请在方法的开头进行一些检查。 For example: 例如:

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(......);
}

It's not the UI's job to compensate for some validation error on the user's input. 在用户的输入上补偿一些验证错误不是UI的工作。 If the data is wrong or missing, don't continue. 如果数据错误或丢失,请勿继续。 It will only cause you strange bugs and lots of pain down the road. 这只会给你带来奇怪的虫子和许多痛苦。

You can also try PluralizationServices service. 您还可以尝试PluralizationServices服务。 Something like this: 像这样的东西:

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");

Try using conditional operator: 尝试使用条件运算符:

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

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

Only addresses the second problem, but: 仅解决第二个问题,但是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM