Cast versus parse

前端 未结 4 806
广开言路
广开言路 2021-02-14 14:19

I\'ve read a few related questions regarding this topic however none of them are making sense to me. As I understand it, in some cases you can use cast and parse interchangeably

4条回答
  •  天命终不由人
    2021-02-14 14:27

    Casting is more of a conversion of an object from a similar type. A good example is float to integer, or double to decimal. Parsing is just that; parsing. The definition or use of parsing is a bit more broad. You could write a Parse method in your own object similar to that of int.Parse or int.TryParse to convert a string to your object type. Parsing could also refer to things such as string manipulation to gather the data you need from any given string. "Parsing" does not necessarily relate to "Casting".

    Another good example of casting is when using inheritance or interfaces.

    public interface ICar {
        // ...
    }
    
    public class Corvette : ICar {
        // ...
    }
    
    public void Foo() {
        Corvette mycar = new Corvette();
        // Now do a cast
        ICar = (ICar)mycar;
    }
    

提交回复
热议问题