C#: Custom casting to a value type

后端 未结 5 2240
不知归路
不知归路 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条回答
  •  萌比男神i
    2021-02-14 10:29

    Another possibility is to write a Parse and TryParse extension method for your class.

    You'd then write your code as follows:

    var x = new Foo();
    var y = int.Parse(x); 
    

提交回复
热议问题