Delegates with same signature

后端 未结 1 725
栀梦
栀梦 2021-01-18 01:52

My question is a bit similar to this one: How to convert an action to a defined delegate of the same signature?

Why there is no implicit convertion between delegates

相关标签:
1条回答
  • 2021-01-18 02:47

    There's no implicit conversion between those two delegates for the same reason that there's no implicit conversion between these two types:

    public sealed class Foo1
    {
        public string Value { get; set; }
    }
    
    public sealed class Foo2
    {
        public string Value { get; set; }
    }
    

    Just because two classes have the same fields doesn't mean that you should be able to treat one as if it were another. The same logic applies to delegates (which are also types, mind you).

    There is semantic meaning applied to the creation of that type. If someone created a Foo1 they want it to be a Foo1, not a Foo2. If they're going out of their way to use a Foo1 where a Foo2 is expected, it's a big red flag that even though the types appear similar, there is a semantic difference between these two types. If the programmer knows something that the compiler doesn't, they can use an explicit conversion of some sort to indicate that they know what they're doing.

    (The previous paragraph was intentionally written to apply equally to your delegates, and the classes I provided above.)

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