警告:这个问题有点异端......宗教程序员总是遵守良好做法,请不要阅读.:)
有谁知道为什么不鼓励使用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) 可能重复:
如何通过"引用"将其分配给c#中的类字段?
大家好 - 请告诉我如何使这项工作?基本上,我需要一个整数引用类型(int*可以在C++中工作)
class Bar
{
private ref int m_ref; // This doesn't exist
public A(ref int val)
{
m_ref = val;
}
public void AddOne()
{
m_ref++;
}
}
class Program
{
static void main()
{
int foo = 7;
Bar b = new Bar(ref foo);
b.AddOne();
Console.WriteLine(foo); // This should print '8'
}
}
Run Code Online (Sandbox Code Playgroud)
我必须使用拳击吗?
编辑: 也许我应该更具体.我正在编写一个BitAccessor类,它只允许访问各个位.这是我想要的用法:
class MyGlorifiedInt
{
private int m_val;
...
public BitAccessor Bits {
return new BitAccessor(m_val);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
MyGlorifiedInt val …Run Code Online (Sandbox Code Playgroud) 我有以下课程:
public class Terminal : IDisposable
{
readonly List<IListener> _listeners;
public Terminal(IEnumerable<IListener> listeners)
{
_listeners = new List<IListener>(listeners);
}
public void Subscribe(ref Action<string> source)
{
source += Broadcast;
//Store the reference somehow?
}
void Broadcast(string message)
{
foreach (var listener in _listeners) listener.Listen(message);
}
public void Dispose()
{
//Unsubscribe from all the stored sources?
}
}
Run Code Online (Sandbox Code Playgroud)
我已经搜索了一段时间,似乎无法存储使用ref关键字传递的参数.尝试将源参数添加到列表或将其分配给字段变量不允许它保持对实际委托的原始引用的引用; 所以我的问题是:
谢谢.
编辑:似乎没有使用包装器或反射,没有解决给定的问题.我的目的是使类尽可能地可移植,而不必将代理包装在辅助类中.谢谢大家的贡献.