gpt4 book ai didi

c# - 打印命名空间而不是字符串值

转载 作者:行者123 更新时间:2023-11-30 21:43:18 31 4
gpt4 key购买 nike

此方法应该打印以下内容:

Creating r1
-> Assigning r2 to r1
-> Changing values of r2
String = This is new info!, Top = 10, Bottom = 50, Left = 10, Right = 50
String = This is new info!, Top = 10, Bottom = 4444, Left = 10, Right = 50

但不是打印字符串值,而是打印字符串所在的类

Creating r1
-> Assigning r2 to r1
-> Changing values of r2
String = Csharp_Projects.Program+ShapeInfo, Top = 10, Bottom = 50, Left = 10, Right = 50
String = Csharp_Projects.Program+ShapeInfo, Top = 10, Bottom = 4444, Left = 10, Right = 50

这是代码:

 using System;

namespace Csharp_Projects
{
static class Program
{
static void Main(string[] args)
{
ShapeInfo.Rectangle.ValueTypeContainingRefType();
}

// this class which takes an string as parameter

public class ShapeInfo
{
public string infoString;

public ShapeInfo(string info)
{
infoString = info;
}

// this struct has two fields, one is int type and the other is ShapeInfo (above) and a constructor which set the values

public struct Rectangle
{
public ShapeInfo rectInfo;

public int recTop, rectleft, rectBottom, rectRight;

public Rectangle(string info, int top, int left, int Buttom, int Right)
{
rectInfo = new ShapeInfo(info);
recTop = top;
rectBottom = Buttom;
rectRight = Right;
rectleft = left;
}
// this method print the results
public void Display()
{
Console.WriteLine("string={0},top={1},Bottom={2},"+"left={3},Right={4}",rectInfo,recTop,rectBottom,rectRight,rectleft);
}

// this method make an object and assign it to second variable and then change the values of second variable .

public static void ValueTypeContainingRefType()
{
Console.WriteLine("Creating r1");
Rectangle r1 = new Rectangle("First Rec", 10, 10, 50, 50);
Console.WriteLine("Assigning r2 to r1");
Rectangle r2 = r1;
Console.WriteLine("Change Values of r2");
r2.rectInfo.infoString = "This is new info!";
r2.rectBottom = 4444;
r1.Display();
r2.Display();
}


}
}
}
}

我真的搞不懂为什么会这样,可能是我对C#系统的了解不够,是什么原因造成的?

最佳答案

您没有在您的 ShapeInfo 类中覆盖 .ToString(),因此系统无法知道您要如何打印该类的实例作为一个字符串。默认情况下,所有对象都打印它们的类名(因为这几乎是每个类唯一可以保证拥有的东西)。

只是override the method :

public override string ToString()
{
return infoString;
}

关于c# - 打印命名空间而不是字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836082/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com