【发布时间】:2014-01-07 19:51:34
【问题描述】:
这是一个奇怪的问题,我让我旁边的高级程序员也感到困惑。完整的问题是我的 ToString() 方法被调用了,我不知道或不明白这是我的代码
static void Main(string[] args)
{
Console.Out.WriteLine("Blank Constructor");
Form form = new Form(); <-- ToString() gets called on this line.
form.ToString();
Console.Read();
}
public Form()
{
FormName = "";
FormImageLocation = "";
FormDescription = "";
FormID = 0;
CreatedDate = DateTime.Now;
LastUpdate = DateTime.Now;
Fields = new List<Field>();
Packets = new List<Packet>(); <-- This line in the constructor
}
public override string ToString()
{
string returnString;
returnString = " Form Name: " + FormName + " Form Image Location: " + FormImageLocation + "Form Description: " + FormDescription + " FormID: " + FormID + " Created Date: " + CreatedDate + " LastUpdate: " + LastUpdate ;
if (fields.Count != 0)
{
foreach (var field in fields)
{
returnString += field.ToString();
}
}
else
{
returnString += "!!! This Form has no Fields !!!";
}
if (Packets.Count != 0)
{
foreach (var packet in Packets)
{
returnString += packet.ToString();
}
}
else
{
returnString += " !!! This Form does not belong to any Packets !!!";
}
Console.Out.WriteLine(returnString);
return returnString;
}
public Packet(string packet_name, List<Form> list_of_forms)
{
PacketName = packet_name;
forms = list_of_forms;
}
这种看似随机的ToString() 打印仅在我逐步执行程序时发生。它将打印在我上面指定的行上,并且当构造函数退出并疯狂打印时,我正在逐步执行ToString() 方法本身。我在ToString() 中放置了一个断点,但它只会在ToString() 被合法调用时停在断点上,所以当我单步执行并执行此随机打印时,它不会停在断点处ToString()。我经历并删除了对ToString() 的所有调用,但它仍然会被随机调用,当我注释掉returnString 变量并返回“她在那里”时,问题就消失了,但这无济于事。如果我只是在没有断点的情况下运行程序,则不会发生此问题。你们中的一些人可能会说,如果它在运行时工作,那没关系,但它让我非常警惕,如果我在路上遇到代码问题,我尝试单步调试代码以找到问题,我会得到不同的结果并妨碍调试。我尝试涵盖整个问题以及我尝试过的内容并提供所需的所有代码,如果我不清楚某些事情,请告诉我,我会再次尝试解释。最后,我在 Windows 7 64 位机器上,我正在使用 Visual Studio C# 2010 Express。
【问题讨论】:
标签: c# visual-studio-2010 debugging tostring