C#: Custom casting to a value type

后端 未结 5 2025
不知归路
不知归路 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;
        }
    
        // ...
    
    0 讨论(0)
  • 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); 
    
    0 讨论(0)
  • 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;
            }
    
        }
    
    0 讨论(0)
  • 2021-02-14 10:38

    Create an explicit or implicit conversion:

    public class Foo
    {
        public static explicit operator int(Foo instance)
        {
            return 0;
        }
    
        public static implicit operator double(Foo instance)
        {
            return 0;
        }
    }
    

    The difference is, with explicit conversions you will have to do the type cast yourself:

    int i = (int) new Foo();
    

    and with implicit conversions, you can just "assign" things:

    double d = new Foo();
    

    MSDN has this to say:

    "By eliminating unnecessary casts, implicit conversions can improve source code readability. However, because implicit conversions do not require programmers to explicitly cast from one type to the other, care must be taken to prevent unexpected results. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. If a conversion operator cannot meet those criteria, it should be marked explicit." (Emphasis mine)

    0 讨论(0)
  • 2021-02-14 10:45

    I would suggest you implement the IConvertible interface as that is designed to handle this. See http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx

    0 讨论(0)
提交回复
热议问题