Is it possible to pass interpolated strings as parameter to a method?

前端 未结 4 502
一整个雨季
一整个雨季 2021-01-04 13:33

I have started to use Interpolated Strings (new feature of C# 6) and it is really useful and gracefully. But according to my needs I have to pass format of string to a metho

4条回答
  •  情话喂你
    2021-01-04 13:46

    It is not possible. But the alternate way is

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

    EDIT:

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

提交回复
热议问题