Cast versus parse

2019-04-06 06:45发布

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 and achieve the same result.

Are there some general guidelines that can help me decide when to choose one approach over the other?

3条回答
姐就是有狂的资本
2楼-- · 2019-04-06 07:06

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;
}
查看更多
一夜七次
3楼-- · 2019-04-06 07:07

You generally use Parse() on a string whose value represents a valid value of the type to which you are converting.

Casting, on the other hand, is better used when you have an object of a derived type but stored in a base variable, and need to use it as its more specific type.

That is, if you have "1234" you can Parse() that into an int. But if you have

object variable = 1234;

You should cast it to get it back as an int.

查看更多
劳资没心,怎么记你
4楼-- · 2019-04-06 07:16

Have a look here, at Mark Gravell's comprehensive answer (will answer you about converting too..).

查看更多
登录 后发表回答