相关疑难解决方法(0)

使用隐式转换重载解析

我基本上想要 string/FormattableString 的两个单独的重载(背景是我想推动人们使用字符串常量来记录日志消息并通过结构化日志而不是日志消息传递参数以简化分析。因此 FormattableString 日志记录方法将被废弃)。

现在由于编译器的工作方式,您不能直接重载方法,因为 FormattableString 在传递之前会转化为字符串。但有效的是有一个定义隐式重载的包装结构:

public struct StringIfNotFormattableStringAdapter
{
    public string StringValue { get; }

    private StringIfNotFormattableStringAdapter(string s)
    {
        StringValue = s;
    }

    public static implicit operator StringIfNotFormattableStringAdapter(string s)
    {
        return new StringIfNotFormattableStringAdapter(s);
    }

    public static implicit operator StringIfNotFormattableStringAdapter(FormattableString fs)
    {
        throw new InvalidOperationException("This only exists to allow correct overload resolution. " +
                                            "This should never be called since the FormattableString overload should be preferred to this.");
    }
}

public static class Test
{
    public static void …
Run Code Online (Sandbox Code Playgroud)

c# language-lawyer overload-resolution

5
推荐指数
1
解决办法
219
查看次数

标签 统计

c# ×1

language-lawyer ×1

overload-resolution ×1