C#:在字符串属性设置器内调用方法时出现问题
我有一个字符串属性,它定义 xml 文件的文件名。当用户将此文件名输入到属性中时,我让设置器在设置“fileName = value”后立即调用 parseXml() 函数,以使用 XML 文件中的数据填充数据表,以便它显示在设计器中。由于某种原因,当我在属性设置器中调用此函数时,每次更改属性时,设置器都会被调用两次,第二次是空字符串,这会导致错误。它为什么要这样做?
public String FileName
{
get { return fileName; }
set
{
fileName = value;
parseXmlFile();
}
}
I have a string property that defines a filename for an xml file. When the user inputs this filename into the property, I have the setter calling a parseXml() function immediatly after setting 'fileName = value' to populate a dataTable with the data from the XML file so it displays in the designer. For some reason, when I have this function call in the property setter, the setter ends up getting called every twice every time I change the property, with the 2nd time being an empty string which causes an error. Why is it doing this?
public String FileName
{
get { return fileName; }
set
{
fileName = value;
parseXmlFile();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我最初的猜测是 parseXml() 中的某些内容再次调用该设置器。如果删除对 parseXml() 的调用会发生什么?您是否尝试过在运行时调试并单步调试代码,以查看第二次调用 setter 的具体内容是什么?
如果您在
filename = value;
上设置断点并点击它,调用堆栈窗口会显示什么?My initial guess would be that something in parseXml() is calling that setter again. What happens if you remove the call to parseXml()? Have you tried debugging and stepping through the code as it is running to see what exactly is calling the setter the second time?
If you slap a breakpoint on
filename = value;
and hit it, what does the callstack window show you?简短的回答:不应该。
更有帮助:也许您自己拨打了第二个电话?在 setter 上设置调试器,第二次调用它时,检查调用堆栈。
Short answer: it shouldn't.
More helpful: maybe you cause the second call yourself? Set the debugger on the setter and the second time it is called, inspect the call stack.
抛开您遇到的问题不谈,将昂贵的 IO 操作放在属性设置器后面有点不合适。
如果您想打开一个文件并解析内容等,最好有一个适当命名的单独方法来执行 IO 并在该方法成功完成其工作时设置此属性(文件名)。
As a complete aside to the problem you're having, putting expensive IO operations behind property setters is a little off kilter.
If you want to open up a file and parse stuff etc it would be better to have a separate method named appropriately that does the IO and sets this property (filename) at the end when the method successfully completed its work.