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

前端 未结 4 520
一整个雨季
一整个雨季 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 13:51

    There are several ways you can do this.

    The first one is to add another method overload that takes a FormattableString (a new typed used by one of the variants of string interpollation) and calls the original one:

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

    And you also have access to the arguments if you need to.

    If you only need the format, just create an extension method to extract it:

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

提交回复
热议问题