收录日期:2021/01/26 16:46:17 时间:2010-03-31 05:06:44 标签:c#,.net

In C++, I have a function:

void MyFunction(int p)
{
    p=5;
}

Assume, I have:

int x = 10;
MyFunction(x); // x = 10
MyFunction(&x); // x = 5

How to archieve this in C# with condition: I create only one MyFunction.

Your C++ function doesn't work the way you think it does. In fact, your code will not compile.

In C#, you would use the ref or out keywords:

void MyFunction1(out int p)
{
    p = 5;
}

void MyFunction2(ref int p)
{
    p = p + 1;
}

int x;
MyFunction1(out x); // x == 5
MyFunction2(ref x); // x == 6

In C# you would need to declare the method with a ref parameter, like this:

void MyFunction(ref int p)
{
    p=5;
}

If you then call it as MyFunction(ref x) the value of x in the caller will be modified. If you don't want it to be modified simply copy it to a dummy variable. You could create an overload of MyFunction that does this internally:

void MyFunction(int p)
{
    MyFunction(ref p);
}

It would technically not be "one function", as you want, but the code wouldn't be duplicated and to any human reading your code it would appear as one - but to the compiler it's two. You would call them like this:

int x = 10;
MyFunction(x); // x = 10
MyFunction(ref x); // x = 5

C# does not have the equivalent functionality. If you declare the method to have a ref parameter, then you must also specify that the parameter is ref type when you call the method.

You need to pass the parameter as reference. If you don't specify it, it automatically creates a copy to work inside the parameter instead of using the same reference.

How to do that? Just specify with the 'ref' word in method declaration:

void MyFunction(ref int p)
{
    p=5;
}

int x = 10;
MyFunction(ref x); // x = 5

The point is that a lot of people think that Reference types are passed by reference and Value types are passed By Value. This is the case from a user's perspective, internally both Reference and Value types are passed By Value only. When a Reference type is passed as a parameter, its value, which is a reference to the actual object is passed. In case of Value types, their value is the value itself (e.g. 5).

StringBuilder sb = new StringBuilder();
SetNull(sb);
SetNull(ref sb);

if SetNull(...) sets the parameter to null, then the second call will set the passed in StringBuilder parameter to null.