C#: Custom casting to a value type

后端 未结 5 2050
不知归路
不知归路 2021-02-14 10:04

Is it possible to cast a custom class to a value type?

Here\'s an example:

var x = new Foo();
var y = (int) x; //Does not compile 

Is i

5条回答
  •  伪装坚强ぢ
    2021-02-14 10:36

    You will have to overload the cast operator.

        public class Foo
        {
            public Foo( double d )
            {
                this.X = d;
            }
    
            public double X
            {
                get;
                private set;
            }
    
    
            public static implicit operator Foo( double d )
            {
                return new Foo (d);
            }
    
            public static explicit operator double( Foo f )
            {
                return f.X;
            }
    
        }
    

提交回复
热议问题