警告:这个问题有点异端......宗教程序员总是遵守良好做法,请不要阅读.:)
有谁知道为什么不鼓励使用TypedReference(隐含地,缺乏文档)?
我已经找到了很好的用途,例如通过不应该是通用的函数传递泛型参数(当使用object可能是过度杀手或缓慢,如果你需要值类型时),当你需要一个不透明的指针时,或者当你需要快速访问数组元素时,你在运行时找到它的规范(使用Array.InternalGetReference).由于CLR甚至不允许错误使用此类型,为什么不鼓励?它似乎不安全或任何东西......
我找到的其他用途TypedReference:
C#中的"Specializing"泛型(这是类型安全的):
static void foo<T>(ref T value)
{
//This is the ONLY way to treat value as int, without boxing/unboxing objects
if (value is int)
{ __refvalue(__makeref(value), int) = 1; }
else { value = default(T); }
}
Run Code Online (Sandbox Code Playgroud)
编写适用于通用指针的代码(如果误用,这是非常不安全的,但如果使用正确则快速且安全):
//This bypasses the restriction that you can't have a pointer to T,
//letting you write very high-performance generic code.
//It's dangerous if you don't know what you're doing, …Run Code Online (Sandbox Code Playgroud)