C# Console.WriteLine对字符串没有输出

huangapple go评论64阅读模式
英文:

C# Console.WriteLine has no output for string

问题

I have a class called Pixel:

class Pixel {   
    public Pixel(int x, int y, string text) {
        int X = x; 
        int Y = y; 
        string Text = text;
    }

    public int X { get; }
    public int Y { get; }
    public string Text { get; }

    public void render() {     
        Console.WriteLine(X);
        Console.WriteLine(Text);
        Console.WriteLine(Y);
    }
}

I then create a new instance of a pixel with some parameters and try to run the render() function:

class Program
{
    static void Main(string[] args) {
        Pixel pixel = new Pixel(0, 0, "X");
        pixel.render();
    }
}

My console output is this:

0
X
0

This output is as expected, and Console.WriteLine works correctly for strings in C#.

英文:

I have a class called Pixel:

class Pixel {   
    public Pixel(int x, int y, string text) {
        int X = x; 
        int Y = y; 
        string Text = text;
    }

    public int X { get; }
    public int Y { get; }
    public string Text { get; }

    public void render() {     
        Console.WriteLine(X);
        Console.WriteLine(Text);
        Console.WriteLine(Y);
    }
}

I then create a new instance of pixel with some parameters and try to run the render() function:

class Program
{
    static void Main(string[] args) {
        Pixel pixel = new Pixel(0, 0, "X");
        pixel.render();
    }
}

My console output is this:

0

0

whereas I would clearly expect "X" on line 2. Why does Console.WriteLine not work for strings? (I originally tried char but I run into the same issue.)

Strangely, if I replace Console.WriteLine(Text); with Console.WriteLine("X") the issue is fixed. I'm new to C# and don't understand this behaviour. Thanks.

答案1

得分: 1

Your Pixel constructor does not update the data members.
Instead it is setting local variables that do not affect the members.

You should change it to:

public Pixel(int x, int y, string text)
{
    X = x;
    Y = y;
    Text = text;
}

Then the output will be:

0
X
0
英文:

Your Pixel constructor does not update the data members.
Instead it is setting local variables that do not affect the members.

You should change it to:

public Pixel(int x, int y, string text)
{
    X = x;
    Y = y;
    Text = text;
}

Then the output will be:

0
X
0

huangapple
  • 本文由 发表于 2023年5月7日 19:19:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定