通用交换难度
我来自 C++,在这里很容易做这样的事情:
template<class T>
void Swap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
然后用它来交换容器中的值:
std::vector<int> someInts;
someInts.push_back(1);
someInts.push_back(2);
Swap(someInts[0], someInts[1]);
但是,在尝试在 C# 中做同样的事情时,
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
我收到错误“属性或索引器可能无法传递为out 或 ref 参数”
这是为什么以及如何克服它?
非常感谢
I'm coming from C++ where it's easy to do something like this:
template<class T>
void Swap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
and then use it to swap values in a container:
std::vector<int> someInts;
someInts.push_back(1);
someInts.push_back(2);
Swap(someInts[0], someInts[1]);
However, upon attempting to do the same thing in C#
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
I get the error "property or indexer may not be passed as an out or ref parameter"
Why is this and how can I overcome it?
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用索引器或属性引用参数。原因是您正在重新调整对对象的引用,而不是位置的引用,因此该函数所产生的任何效果实际上都不会更改源,因为它不会将其写回到该位置(即,在财产)。您需要将数组传递到方法中,以便该方法可以设置值和索引以及知道要交换哪些值。
You cannot use indexers or properties ref parameters. The reason is you are retuning a reference to the object but not the location so any effect the function would have would not actually change the source as it wouldn't write it back to the location (i.e. not call the setter in the case of a property). You need to pass the array into the method so that the method can set values an indexes as well as know what values to swap.
属性和索引器实际上是方法(由编译器在幕后创建),因此我认为不可能对它们进行按引用调用。但是你可以编写这样的方法:
Properties and the indexer are actually methods (created by the compiler behind the scenes), so I suppose it is not possible to do call-by-reference on them. However you could write a method like this: