C#: Custom casting to a value type

后端 未结 5 2044
不知归路
不知归路 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:22

    You need to define explicit or implicit casting:

    public class Foo
    {
        public static implicit operator int(Foo d)
        {
            return d.SomeIntProperty;
        }
    
        // ...
    

提交回复
热议问题