0

I was looking through the source of my NHibernate project (version 3.3.1.4000) and I just noticed something strange in the AnywhereMatchMode class:

public override string ToMatchString(string pattern)
{
    return (string) (object) '%' + (object) pattern + (string) (object) '%';
}

Why on earth would they cast a char to an object and immediately re-cast it to a string? Why cast a string to an object before adding it to other strings? Is there a performance bonus here, or an edge case to avoid? I'm looking for the idea behind this code, because there must be a reason for it.

Note: I just realized, I got here with ReSharper's "Navigate To" feature, so this may be decompiled code I'm looking at. Even if it is, I'd like to know what's going on here.

4

1 回答 1

5

看起来它可能只是 ReSharper 的“导航到”的工件,查看 NHibernate 的源代码,该方法如下所示:

public override string ToMatchString(string pattern)
{
    return '%' + pattern + '%';
}

NHibernate 源代码

更新:这是此方法的 MSIL:

.method public hidebysig virtual instance string 
        ToMatchString(string pattern) cil managed
{
  // Code size       26 (0x1a)
  .maxstack  3
  .locals init ([0] string CS$1$0000)
  IL_0000:  nop
  IL_0001:  ldc.i4.s   37
  IL_0003:  box        [mscorlib]System.Char
  IL_0008:  ldarg.1
  IL_0009:  ldc.i4.s   37
  IL_000b:  box        [mscorlib]System.Char
  IL_0010:  call       string [mscorlib]System.String::Concat(object,
                                                              object,
                                                              object)
  IL_0015:  stloc.0
  IL_0016:  br.s       IL_0018
  IL_0018:  ldloc.0
  IL_0019:  ret
} // end of method AnywhereMatchMode::ToMatchString

由于代码将字符串连接编译为优化string.Concat("%", pattern, "%")后的 .Resharper 反编译时,它看起来可能将装箱表示为强制转换为object.

于 2013-07-25T17:32:03.570 回答