Calling overloaded method with generic property calls wrong overload

前端 未结 1 449
小蘑菇
小蘑菇 2020-12-07 03:31

I have a basic filter class that stores a string parameter name and a generic T value. The filter has a method Write(writer As IWriter)

1条回答
  •  -上瘾入骨i
    2020-12-07 03:55

    The problem is, when I call writer.Write(ParameterName, Value) and T is a string, it calls the overload for string/object, not string/string!

    Yes, this is expected - or rather, it's behaving as specified. The compiler chooses the overload based on the compile-time types of the arguments, usually. There's no implicit conversion from T to string, so the only applicable candidate for the invocation of writer.Write(ParameterName, Value) is the Write(string, object) overload.

    If you want it to perform overload resolution at execution time, you need to use dynamic typing. For example:

    public void Write(FooWriter writer) {
        // Force overload resolution at execution-time, with the execution-time type of
        // Value.
        dynamic d = Value;
        writer.Write(ParameterName, d);
    }
    

    Note that this could still behave unexpectedly - if Value is null, then it would be equivalent to calling writer.Write(ParameterName, null) which would use the "better" function member - here writer.Write(string, string) - even if the type of T is object!

    0 讨论(0)
提交回复
热议问题