Typecasting in C#

后端 未结 5 1130
Happy的楠姐
Happy的楠姐 2020-11-29 06:17

What is type casting, what\'s the use of it? How does it work?

5条回答
  •  无人及你
    2020-11-29 06:25

    Also, if you're explicitly casting, you can take advantage of pattern matching. If you have an object:

    object aObject = "My string value";
    

    You can safely cast the object as a string in a single line:

    if (aObject is string aString)
    {
        Console.WriteLine("aString = " + aString)
        // Output: "aString = My string value"
    }
    

    Using this, along with an inverted if statement, you can safely cast types, and fail out early if need be:

    public void Conversion(object objA, object objB)
    {
        // Fail out early if the objects provided are not the correct type, or are null
        if (!(objA is string str) || !(objB is int num)) { return; }
    
        // Now, you have `str` and `num` that are safely cast, non-null variables
        // all while maintaining the same scope as your Conversion method
        Console.WriteLine("str.Length is " + str.Length);
        Console.WriteLine("num is " + num);
    }
    

提交回复
热议问题