2017-04-20 57 views
0
string q1 = "What Company during the {0}, {1},{2},{3} tax years?" 
q1 = string.Format(q1, model.CurYear, model.Year2, model.Year3, model.Year4); 

来了我可能有year2,year3,year4或不是它可能包含null。 所以有任何可选参数的范围。 错误消息:我收到你有更多的参数列表,所以有任何解决方案。我可以在string.format中有可选参数吗?

回答

0

您可以检查null并使用三元操作替换string.empty的null。否则,请先检查空值,然后针对每种情况使用不同的格式字符串

0

您应该检查字符串是否为空并放入string.Empty,但应在年份文本中包含逗号;如果你不这样做,你会得到一个文字,例如“在{0} ,, {3}纳税年度的什么公司?”

0

你可以在模型中的所有其他只读属性收集所有年份作为列表/任何和使用此列表来获取所有非空年。

喜欢的东西:

class YourModelClass 
{ 
    public int? Year2 { get; set; } 
    public int? Year3 { get; set; } 
    public int? Year4 { get; set; } 

    public List<int?> Years => new List<int?> {Year2, Year3, Year4}; 
} 

    YourModelClass model = new YourModelClass(); 
    string result = $"What Company during the {string.Join(",", model.Years.Where(a => a != null).ToList())} tax years?"; 
0

可以使用null-coalescing operator??)是这样的:

string a = null; 
string b = "smthing"; 
string c = "nothing?"; 
string d = null; 
string someString = string.Format 
     ("this is a string with \"optional\" parameters {0} {1} {2} {3}", 
     a ?? "", 
     b ?? "", 
     c ?? "", 
     d ?? ""); 

它执行以下操作:
使用其自身的价值,除非null再利用价值在右边??

这是一个基因回答然而,你需要,'s,所以你必须以某种方式建立字符串。

0

有三样东西:

  1. 格式不断变化的年代字符串。

    string format = "What Company during the {0} tax years?" 
    q1 = string.Format(format, yearsList); 
    
  2. 过滤器列表(非.net列表)的年。

    years = new []{model.CurYear, model.Year2, model.Year3, model.Year4] 
           .Where(y => y != null); 
    
  3. 用','加入年份字符串。

    yearsList = String.Join(", ", years); 
    

把它们放在一起:

q1 = String.Format(
     "What Company during the {0} tax years?", 
     String.Join(
      ", ", 
      new []{model.CurYear, model.Year2, model.Year3, model.Year4] 
       .Where(y => y!=null)) 
相关问题