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

How*_*ley 7 c# debugging clr service

这个真让我难过.我和另一位打电话给我的开发商合作,因为他无法相信他所看到的.我们一起调试了调试器,我也看到了它并没有解释.这是场景.他正在编写一个方法,通过自动生成的COM包装器与第三方COM对象进行交互(仅通过添加COM组件作为参考生成.这是他的方法的顶部:

  public bool RefolderDocument(ref IManDocument oDoc)
    {
        string strCustom1 = (string) oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom1);
        string strCustom2 = (string) oDoc.GetAttributeValueByID(imProfileAttributeID.imProfileCustom2);
Run Code Online (Sandbox Code Playgroud)

代码的目的是从"文档"对象(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));
Run Code Online (Sandbox Code Playgroud)

结果相同!我们此时正在抓住吸管,并将代码从.NET 4中删除到.NET 3.5(CLR 2),但没有变化.一个可能相关的观点是,这是一项服务,我们将附加到服务流程.构建目标是x86,服务位置肯定在Debug输出构建文件夹中.

这有什么合理的解释吗?我很难过如何继续.

Mar*_*lan 1

看起来 strCustom1 和 strCustom2 都已设置为对 GetAttributeValueByID 结果的引用。我不知道为什么,看看这里的其他人是否可以(寻呼斯基特博士,哈哈……)会很有趣。

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

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

我的想法基本上是让它评估表达式而不是直接使用引用......

马丁.

诗。string.Copy() 是怎么回事?