开发者

Why are C# calls different for overloaded methods for different values of the same type?

I have one doubt concerning c# method overloading and call resolution.

Let's suppose I have the following C# code:

enum MyEnum { Value1, Value2 }

public void test() {
    method(0); // this calls method(MyEnum)
    method(1); // this calls method(object)
}

public void method(object o) {
}

public void method(MyEnum e) {
}

Note that I know how to make it w开发者_运维技巧ork but I would like to know why for one value of int (0) it calls one method and for another (1) it calls another. It sounds awkward since both values have the same type (int) but they are "linked" for different methods.


Literal 0 is implicitly convertible to any enum type, which is a closer match than object. Spec.

See, for example, these blog posts.


I'm pretty sure to call

public void method(MyEnum e) {
}

properly you need to pass in MyEnum.Value1 or MyEnum.Value2. Enum != int type, hence why you have to cast the int to your enum type. So (MyEnum)1 or (MyEnum)0 would work properly.

In your case, 0 was implicitly cast to your enum type.


Why does C# allow implicit conversion of literal zero to any enum? is a good reference that has a great answer by JaredPar in it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜