c# - 设置一个 c# 方法范围的变量如何影响另一个?

标签 c# service clr debugging

这个真的让我难住了。我正在与另一个给我打电话的开发人员一起工作,因为他无法相信自己所看到的。我们一起调试调试器,我也看到了,但没有解释。这是场景。他正在编写一种方法,通过自动生成的 COM 包装器与第 3 方 COM 对象进行交互(只需添加 COM 组件作为引用即可生成。这是他的方法的顶部:

  public bool RefolderDocument(ref IManDocument oDoc)
    {
        string strCustom1 = (string) oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom1);
        string strCustom2 = (string) oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom2);

该代码的目的是从“文档”对象 (oDoc) 中获取项目编号和子项目编号。

这是您逐步执行时发生的情况。在第一次分配后,strCustom1 具有预期值“32344”(项目编号),而 strCustom2 如预期的那样为空。第二次赋值后,strCustom2得到子项目号“0002”——但是strCustom1已经变成了32334——一个字符变了!?

我觉得这是某种老派的 c 语言堆栈溢出(我不希望在托管应用程序中出现这种情况,即使它与 COM 组件进行互操作)。我们都一头雾水。为了解决这种奇怪的问题,我尝试将第一个字符串的内容复制到另一个位置,如下所示:

  public bool RefolderDocument(ref IManDocument oDoc)
    {
        string strCustom1 = string.Copy((string)oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom1));
        string strCustom2 = string.Copy((string)oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom2));

同样的结果!此时我们捕获了救命稻草,将代码从 .NET 4 删除到 .NET 3.5 (CLR 2),但没有任何变化。可能相关的一点是,这是一项服务,我们正在附加到服务流程。该构建针对 x86,服务位置肯定在 Debug 输出构建文件夹中。

这有什么合乎逻辑的解释吗?我对如何进行感到困惑。

最佳答案

看起来 strCustom1 和 strCustom2 都被设置为对 GetAttributeValueByID 结果的引用。我不知道为什么,看看这里是否有其他人(传呼 Skeet 博士 lol...)可以很有趣。

但在短期内,我认为您会发现这会为您解决问题...

 public bool RefolderDocument(ref IManDocument oDoc)
    {
        string strCustom1 = "" + string.Copy((string)oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom1));
        string strCustom2 = "" + string.Copy((string)oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom2));

我的想法基本上是让它计算一个表达式而不是直接使用引用...

马丁。

附言。 string.Copy() 有什么用?

关于c# - 设置一个 c# 方法范围的变量如何影响另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5502429/

相关文章:

c# - 枚举作为其自己的自定义属性构造函数的参数

c# - 线程环境下的redis不一致

c++ - Windows 服务状态 C++?

c# - 什么时候在 C# 中触发垃圾回收?

service - sails.js 使用查找查询时,服务返回对象未定义

c# - 为什么 WCF/Mongo 抛出异常 : An item with the same key has already been added

c# - 奇怪的异常行为......为什么?

c# - 垃圾收集器不再有引用

c# - 松散的 XAML 是根据引用的命名空间加载的 .NET/CLR 版本吗?

c# - 从 C# 中的另一个 private void 调用 private void