有没有在框架的通用互换的方法? [英] Is there a generic swap method in the framework?

查看:76
本文介绍了有没有在框架的通用互换的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问这样的方法框架存在的任何地方?

Does a method like this exist anywhere in the framework?

public static void Swap<T>(ref T left, ref T right) {
    T temp;
    temp = left;
    left = right;
    right = temp;
}

如果没有,有什么理由?

If not, any reason why?

推荐答案

有<一个href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.exchange.aspx">Interlocked.Exchange.这确实是一个线程安全的,原子的呼叫。

There is Interlocked.Exchange. This does it in a thread-safe, atomic call.


意见后编辑:

我想弄清楚它是如何工作使用Interlocked.Exchange,你会怎么做:

Just to clarify how this works using Interlocked.Exchange, you would do:

left = Interlocked.Exchange(ref right, left);

这将是等效的(实际上)做:

This will be the equivalent (in effect) to doing:

Swap(ref left, ref right);

不过,Interlocked.Exchange这是否是一个原子操作,所以它是线程安全的。

However, Interlocked.Exchange does this as an atomic operation, so it's threadsafe.

这篇关于有没有在框架的通用互换的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆