反编译 .NET Replace 方法 (v4.6.1)

decompile .NET Replace method (v4.6.1)

我想看看

public String Replace(String oldValue, String newValue);

mscorlib.dll (System.String) 中的方法有效。

我用 dotPeek 反编译了 mscorlib.dll,在方法内部调用了 ReplaceInternal 方法,但我找不到它

string s = ReplaceInternal(oldValue, newValue);

我什至在 GIT 的开源 .NET Core 上搜索过此方法,但没有成功。

请说明这个方法在哪里,里面有什么?

看看here,你会注意到:

// This method contains the same functionality as StringBuilder Replace. 
// The only difference is that
// a new String has to be allocated since Strings are immutable
[System.Security.SecuritySafeCritical]  // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String ReplaceInternal(String oldValue, String newValue);

extern关键字means表示此方法是在外部实现的,在另一个dll中。

话虽这么说,它甚至可能是用这个模块使用的非托管 dll 编写的(很可能是用 C++ 编写的)。因此您无法反编译或查看此代码,就像您通常对托管代码所做的那样。

更新

经过一番搜索,我在coreclr项目中找到了相应的代码:

https://github.com/dotnet/coreclr/blob/master/src/classlibnative/bcltype/stringnative.cpp

外部 C++ 代码在这里。

https://github.com/gbarnett/shared-source-cli-2.0/blob/master/clr/src/vm/comstring.cpp

第 1578 行有

FCIMPL3(Object*, COMString::ReplaceString, StringObject* thisRefUNSAFE, StringObject* oldValueUNSAFE, StringObject* newValueUNSAFE)

要了解函数的工作原理,请查看 http://referencesource.microsoft.com/ 下的参考源。

搜索 mscorlib,转到 System.String,搜索 Replace 并查看:http://referencesource.microsoft.com/#mscorlib/system/string.cs,69fc1d0aa6df8a90,references