此方法应打印以下内容:
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#系统的了解还不够,是什么原因造成的?
答案 0 :(得分:2)
您不会覆盖.ToString()
类中的ShapeInfo
,因此系统无法知道您希望如何将该类的实例打印为字符串。默认情况下,所有对象都会打印它们的类名(因为这几乎是每个类都保证的唯一对象)。
public override string ToString()
{
return infoString;
}
答案 1 :(得分:1)
您需要覆盖ShapeInfo中的ToString方法以返回infoString。
/es/investigacion/lace/(programa-maestrias|alumni|investigacion|programa-maestrias|alumni/latin-american-forum-entrepreneurs|alumni/fondo-angel-investment|fondo-inversion|investigacion|acerca-del-centro|alumni/estudiantes-del-pais|alumni/mentoring|alumni/incae-entrepreneur-award)\.html|
或者更改要使用的DisplayMethod rectInfo.infoString而不是rectInfo
public override string ToString()
{
return infoString;
}