是否可以将插值字符串作为参数传递给方法?

我已经开始使用Interpolated Strings (C#6的新function),它非常有用且优雅。 但根据我的需要,我必须将字符串格式作为参数传递给方法。 像下一个:

MyMethod(string format) 

在过去,我在下一个方面使用它:

 MyMethod("AAA{0:00}") 

现在我尝试了这段代码:

 MyMethod($"AAA{i:00}") 

但这不起作用,因为i是在方法内部创建的,并且在此上下文中超出了范围。

是否可以使用任何技巧将插值字符串作为参数传递给方法?

你不能那样做,这也不是一个好主意 – 它意味着你正在使用另一种方法的局部变量。
这将破坏此function的目的 – 使编译器可validation字符串插值并绑定到局部变量。

C#有几个不错的选择。 例如,使用Func

 public void MyMethod(Func formatNumber) { int i = 3; var formatted = formatNumber(i); } 

用于:

 MyMethod(number => $"AAA{number:00}"); 

这比你现在拥有的要好 – 你有格式字符串(s?)及其在不同地方的用法。

如果您有多个变量,这种方法可以扩展,但考虑将它们分组到一个类(或结构)中 – func看起来会更好,并且您的代码将更具可读性。 这个类也可以覆盖.ToString() ,这可能对你有用。

另一个简单的选择是仅传递格式: MyMethod("00")i.ToString(format) ,但这仅适用于您可能简化的示例。

有几种方法可以做到这一点。

第一个是添加另一个方法重载,它接受FormattableString (由字符串interpollat​​ion的一个变体使用的新类型)并调用原始的:

 public void MyMethod(FormattableString fs) { MyMethod(fs.Format); } 

如果需要,您还可以访问参数。

如果您只需要格式,只需创建一个扩展方法来提取它:

 public static string AsFormat(FormattableString fs) { return fs.Format; } 

这不可能。 但另一种方式是

 public static string MyMethod(string format, params object[] args) { if (format == null || args == null) throw new ArgumentNullException(format == null ? "format" : "args"); return string.Format((IFormatProvider) null, format, args); } 

编辑:

 MyMethod("The number is {0}", 12); 

EDIT2:

 public static string MyMethod(string format) { var i = 12; var result = string.Format(null, format, i); return result; } MyMethod("{0:000}"); 

几年以来,当我被问到这个问题时,我在搜索到我已经掌握的答案时遇到了这个问题,但无法理解实现/语法。

我的解决方案是@Kobi提供的更多…

 public class Person { public int Id {get; set;} public DateTime DoB {get;set;} public String Name {get;set;} } public class MyResolver { public Func Resolve {get;set;} public string ResolveToString(T r) where T : Person { return this.Resolve(r); } } // code to use here... var employee = new Person(); employee.Id = 1234; employee.Name = "John"; employee.DoB = new DateTime(1977,1,1); var resolver = new MyResolver(); resolver.Resolve = x => $"This person is called {x.Name}, DoB is {x.DoB.ToString()} and their Id is {x.Id}"; Console.WriteLine(resolver.ResolveToString(employee)); 

我没有测试上面的语法错误,但希望你能得到这个想法,现在你可以定义你希望字符串看起来“如何”,但是在运行时根据Person对象中的值保留空白。

干杯,

韦恩