Methods with classname as a return type

前端 未结 2 826
鱼传尺愫
鱼传尺愫 2021-01-29 03:35

I\'m new in c# or any type of programming language. When I see codes in c# I found there are lot of confusions are over here. one of them I want to clarify from here. Methods co

2条回答
  •  抹茶落季
    2021-01-29 04:26

    So if we have a class Triangle and a method GetTriangle which has the parameter isBlue.

    public class Triangle
    {
        public string Colour { get; set; }
    }
    
    public Triangle GetTriangle(bool isBlue)
    {
        Triangle resultTriangle;
    
        if (isBlue)
        {
            resultTriangle = new Triangle { Colour = "Blue" };
        }
        else
        {
            resultTriangle = new Triangle { Colour = "Red" };
        }
    
        return resultTriangle;
    }
    

    We can call GetTriangle with an argument of true or false like so:

    Triangle blueTriangle = GetTriangle(true);
    
    Triangle redTriangle = GetTriangle(false);
    

    Both of the results of GetTriangle are Triangles, even though they contain different data (in this case a different Colour).

    Like a child's wood-block toy, the compiler checks what the "shape" of the data is, not what colour it is. So if you try to return a Square from a method which returns Triangle then the compiler will throw an error in the same way you wouldn't be able to put a square block in a triangle hole.

提交回复
热议问题