如何在方法内向下转换 ref 变量
我需要在将 long 作为 ref 变量传递的方法中将 long 向下转换为 int:
public void Foo(ref long l)
{
// need to consume l as an int
}
我怎样才能轻松地做到这一点?
I need to downcast a long to an int in a method where the long is passed as a ref variable:
public void Foo(ref long l)
{
// need to consume l as an int
}
How can I easily do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能。 但是,您想要放入
ref int
中的任何值都可以放入ref long
中 - 您只需担心初始值以及您想要的值。如果它超出了int
的范围,则想要执行此操作。您需要在代码中的多少个位置写入 ref 参数或读取它? 如果只有一两个地方,你只要在正确的时间进行适当的施法就可以了。 否则,您可能想引入一种新方法:
我在评论中说它不是行为的精确模仿的原因是,通常对原始 ref 参数的更改即使在方法返回之前也是可见的,但现在它们只会在最后可见。 此外,如果该方法引发异常,则该值不会更改。 后者可以用 try/finally 来修复,但这有点笨拙。 事实上,如果您想要 try/finally 行为,您可以轻松地通过一个方法完成这一切:
You can't. However, any value you want to put into a
ref int
can be put into aref long
anyway - you've just got to worry about the initial value, and what you want to do if it's outside the range ofint
.How many places do you need to write to the ref parameter or read it within your code? If it's only in one or two places, you should be okay just to cast appropriately at the right times. Otherwise, you might want to introduce a new method:
The reason I say in the comments that it's not an exact mimic for the behaviour is that normally changes to the original ref parameter are visible even before the method returns, but now they'll only be visible at the very end. Also, if the method throws an exception, the value won't have been changed. The latter could be fixed with try/finally, but that's a bit clunky. In fact, if you want the try/finally behaviour you can do it all in a single method easily:
你不知道。 您不能将您的参考指向不同的类型。 调用您的方法的代码如何知道它已更改?
如果您只想将值作为
int
使用,那么您可以执行以下操作:You don't. You can't take your reference and point it to a different type. How would the code calling your method know that it's changed?
If you just want to work with the value as an
int
, then you could do something like this:您对细节了解不多,但如果您正在谈论这种情况:
请尝试以下操作:
You're a little light on the details, but if you're talking about this scenario:
try this:
无论它是否可为空,都不能安全地将 long 转换为 int,因为它有可能溢出。
尝试这个
You can't safely cast a long to an int regardless of whether it's nullable or not as theres a chance it will overflow.
try this
你不能直接施放这个。 最好的选择是将其转换为本地变量,然后在方法末尾分配它。
You cannot directly cast this. The best option would be to cast it to a local, then assign it at the end of your method.