Can I check if a variable can be cast to a specified type?

后端 未结 7 2223
误落风尘
误落风尘 2020-12-15 15:50

I am trying to verify whether a variable that is passed can be converted to a specific type. I have tried the following but can\'t get it to compile so I assume I\'m going

7条回答
  •  没有蜡笔的小新
    2020-12-15 16:09

    I think this is what you're looking for:

    var myValue = "42";
    int parsedValue;
    
    if (Int32.TryParse(myValue, out parsedValue)) {
        // it worked, and parsedValue is equal to 42
    }
    else {
        // it did not work and parsedValue is unmodified
    }
    

    EDIT: Just to be clear, the operators is and as are used in the following ways...

    The is operator will return a boolean value to indicate whether or not the object being tested either is the type specified or implements the interface specified. It's like asking the compiler "Is my variable this type?":

    var someString = "test";
    var result = someString is IComparable; // result will be true
    

    The as operator attempts to perform the conversion, and returns a null reference if it can't. This is like telling the compiler "I would like to use this variable as this type":

    var someString = "test";
    var comparable = someString as IComparable; // comparable will be of type String
    

    If you tried to do this:

    var someString = "42";
    // using Int32? because the type must be a reference type to be used with as operator
    var someIntValue = someString as Int32?;
    

    The compiler will issue an error:

    Cannot convert type via a built-in converstion.

提交回复
热议问题