質問

I have an explicit conversion setup between two reference types.

class Car
{
    public void Foo(Car car)
    {

    }

    public static explicit operator Bike(Car car)
    {
        return new Bike();
    }

}

class Bike
{

}

If I invoke Foo and pass a type of Bike, then I must perform an explicit conversion.

            Car myCar = new Car();
            Bike bike = (Bike)myCar;            
            myCar.Foo(bike);//Error: Cannot convert from Bike to Car.

However, if I add an extension method, then explicit conversio is no longer required.

        public static void Foo(this Car car, Bike bike)
        {
            car.Foo(bike);//Success...
        }

Why is the extension method able to invoke Foo with a type of Bike implicitly?

役に立ちましたか?

解決 2

Now that you've modified the code to show;

public static void Foo(this Car car, Bike bike)
{
    car.Foo(bike);//Success...
}

All you've done is create an ironic StackOverflowException. This method is now just calling itself recursively, not the implementation of Foo in Car.

TIP: Get yourself a copy of ReSharper - it'll put a nice circle-arrow icon on this line of code to show you what's going on without actually needing to compile or run it. :-)

他のヒント

Why is the extension method able to invoke Foo with a type of Bike implicitly?

It's not. The code you provided results in a compiler error.

At least one of the following is true:

  1. The code you provided here is not the code you're trying to compile.
  2. You have an implicit conversion in your code that you didn't add here.
  3. You just haven't actually compiled your code and haven't noticed that it won't compile.

Shouldn't your explicit conversion should be defined on Bike?

class Bike
{
    public static explicit operator Bike(Car car)
    {
        return new Bike();
    }
}

This allows:

Car myCar = new Car();
Bike myBike = (Bike) myCar;

If you want to be able to do this without specifying the conversion, you should use the implicit keyword.

Car myCar = new Car();
Bike myBike = myCar;

And finally, where you are getting the error //Error: Cannot convert from Bike to Car. This indicates you need the inverse conversion...

class Car
{
    // FROM Bike TO Car
    public static explicit operator Car(Bike bike)
    {
        return new Car();
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top