Are ref and out in C# the same a pointers in C++?

2019-02-13 01:56发布

I just made a Swap routine in C# like this:

static void Swap(ref int x, ref int y)
{
    int temp = x;
    x = y;
    y = temp;
}

It does the same thing that this C++ code does:

void swap(int *d1, int *d2)
{
    int temp=*d1;
    *d1=*d2;
    *d2=temp;
}

So are the ref and out keywords like pointers for C# without using unsafe code?

7条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-13 02:31

Reference parameters in C# can be used to replace one use of pointers, yes. But not all.

Another common use for pointers is as a means for iterating over an array. Out/ref parameters can not do that, so no, they are not "the same as pointers".

查看更多
放荡不羁爱自由
3楼-- · 2019-02-13 02:44

The short answer is Yes (similar functionality, but not exactly the same mechanism). As a side note, if you use FxCop to analyse your code, using out and ref will result in a "Microsoft.Design" error of "CA1045:DoNotPassTypesByReference."

查看更多
祖国的老花朵
4楼-- · 2019-02-13 02:45

While comparisons are in the eye of the beholder...I say no. 'ref' changes the calling convention but not the type of the parameters. In your C++ example, d1 and d2 are of type int*. In C# they are still Int32's, they just happen to be passed by reference instead of by value.

By the way, your C++ code doesn't really swap its inputs in the traditional sense. Generalizing it like so:

template<typename T>
void swap(T *d1, T *d2)
{
    T temp = *d1;
    *d1 = *d2;
    *d2 = temp;
}

...won't work unless all types T have copy constructors, and even then will be much more inefficient than swapping pointers.

查看更多
Fickle 薄情
5楼-- · 2019-02-13 02:46

Actually, I'd compare them to C++ references rather than pointers. Pointers, in C++ and C, are a more general concept, and references will do what you want.

All of these are undoubtedly pointers under the covers, of course.

查看更多
虎瘦雄心在
6楼-- · 2019-02-13 02:54

ref and out are only used with function arguments to signify that the argument is to be passed by reference instead of value. In this sense, yes, they are somewhat like pointers in C++ (more like references actually). Read more about it in this article.

查看更多
霸刀☆藐视天下
7楼-- · 2019-02-13 02:55

The nice thing about using out is that you're guaranteed that the item will be assigned a value -- you will get a compile error if not.

查看更多
登录 后发表回答