jyo*_*ora 0 .net c# casting ref-parameters
我需要在一个方法中将long转发为int,其中long作为ref变量传递:
public void Foo(ref long l)
{
// need to consume l as an int
}
Run Code Online (Sandbox Code Playgroud)
我怎么能轻松做到这一点?
你不能.但是,无论如何,你想要放入的任何值ref int都可以放入ref long- 你只需要担心初始值,以及如果它超出范围,你想要做什么int.
您需要在ref参数中写入多少个位置或在代码中读取它?如果它只在一两个地方,你应该可以在正确的时间适当地投射.否则,您可能想要引入一个新方法:
public void Foo(ref int x)
{
// Here's the body I *really* want
}
public void Foo(ref long x)
{
// But I'm forced to use this signature for whatever
// reasons. Oh well. This hack isn't an *exact* mimic
// of ref behaviour, but it's close.
// TODO: Decide an overflow policy
int tmp = (int) x;
Foo(ref tmp);
x = tmp;
}
Run Code Online (Sandbox Code Playgroud)
我在评论中说这不是对行为的精确模仿的原因是,即使在方法返回之前,通常对原始ref参数的更改也是可见的,但现在它们仅在最后可见.此外,如果方法抛出异常,则不会更改该值.后者可以通过try/finally修复,但这有点笨拙.实际上,如果您想要try/finally行为,您可以轻松地在一个方法中完成所有操作:
public void Foo(ref long x)
{
int y = (int) x;
try
{
// Main body of code
}
finally
{
x = y;
}
}
Run Code Online (Sandbox Code Playgroud)