How do I cast Class FooObject to class BarObject which both implement interface IObject? [duplicate]

落花浮王杯 提交于 2019-12-21 19:41:13

问题


I have 2 classes which implement the same interface. But somehow I cannot cast them from one to another.

Here's an example:

public interface IObject {
    // ...
}

public class FooObject : IObject {
    // ...
}

public class BarObject : IObject {
    // ...
}

-

If I do it like this, VS will mark it as Cannot convert type 'FooObject' to 'BarObject'

var foo = new FooObject();
var bar = (BarObject)foo; // Build error

-

If I do it like this, there is no build error, but when called, it throw System.InvalidCastException: Unable to cast object of type 'FooObject' to 'BarObject'.

var foo = new FooObject();
var bar = (BarObject)(IObject)foo; // No build error, but InvalidCastException gets thrown

-

So, how do I cast/parse/convert an implementation (FooObject) of an interface (IObject) to another implementation (BarObject) of that same interface?

Solution:

I fixed this by creating an explicit conversion operator:

public class FooObject {
    // ...
    public static explicit operator BarObject(FooObject fooObject)
    {
        // ...
    }
}

Thanks to CodeCaster.

来源:https://stackoverflow.com/questions/55047418/how-do-i-cast-class-fooobject-to-class-barobject-which-both-implement-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!