英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论