Casting between two types derived from the (same) interface

前端 未结 9 2042
南方客
南方客 2020-12-20 12:55

I have an interface and two types that derive from it.

However, I cannot do the following:

B objectB = (B) objectA

Where B derives

9条回答
  •  鱼传尺愫
    2020-12-20 13:24

    An object is assignable to an ancestor (direct or indirect base type) or to an interface it implements, but not to siblings (i.e. another type deriving from a common ancestor); however, you can declare your own explicit conversions:

    class FooObject : IObject
    {
        public string Name { get; set; }
        public int Value { get; set; }
    
        public static explicit operator FooObject(BarObject bar)
        {
            return new FooObject { Name = bar.Name, Value = bar.Value };
        }
    }
    
    class BarObject : IObject
    {
        public string Name { get; set; }
        public int Value { get; set; }
    
        public static explicit operator BarObject(FooObject bar)
        {
            return new BarObject { Name = bar.Name, Value = bar.Value };
        }
    }
    

    Now you can write

    var foo = new FooObject();
    var bar = (BarObject)foo;
    

    or

    var bar = new BarObject();
    var foo = (FooObject)bar;
    

    without getting errors.

    You can also create implicit conversions, if it feels natural. E.g. int is implicitly convertible to double: int i = 5; double x = i;.

    (This is also an answer to the closed question How do I cast Class FooObject to class BarObject which both implement interface IObject?).

提交回复
热议问题