Odd class member syntax shown in ILSpy
-
01-06-2021 - |
質問
I'm poking around a few dlls within the XNA framework using ILSpy and came across this:
class KerningHelper
{
private void !KerningHelper()
{
((IDisposable)this).Dispose();
}
}
What is the exclamation mark for in the above? Is it an issue with ILSpy, or something else?
Note, the class has a separate destructor: private unsafe void ~KerningHelper()
.
解決
As the comments stated, the exclamation mark is the C++/CLI marker for a finalizer method. Unlike traditional C++ destructors (~) that are called when you explicitly dispose of an object, finalizers are called by the garbage collector thread. You can see the official details here.
I would expect ILSpy to translate the !KerningHelper()
to ~KerningHelper()
, since C++/CLI finalizer is equivalent to C#'s destructor - it's a non-deterministic method that occurs when the GC gets to it, unlike C++/CLI's explicit ~destructor, which is called when you call delete
or an explicit Dispose call is made.