method with ref object parameter
Hi i have to call a method that has this signature:
int MethodName(ref object vIndexKey)
If i try to call it with
String c = "690";
MethodNam开发者_如何学Ce(ref (object) c);
It doesn't work.
How can i do?
thanks
You need to do it like this:
String c = "690";
object o = (object) c;
MethodName(ref o);
The reason is that the parameter must be assignable by the function. The function could do something like this:
o = new List<int>();
Which is not possible if the underlying type is a string that has been casted to an object during the method call, because the target of the assignment would still be a string and not an object.
When a method has a ref parameter, the argument type has to match the parameter type exactly. Suppose MethodName
were implemented like this:
public void MethodName(ref object x)
{
x = new object();
}
What would you expect to happen if you were able to call it with just ref c
? It would be trying to write a reference to a plain System.Object
into a variable of type System.String
, thus breaking type safety.
So, you need to have a variable of type object
. You can do that as shown in klausbyskov's answer, but be aware that the value won't then be copied back to the original variable. You can do this with a cast, but be aware that it may fail:
string c = "690";
object o = c;
MethodName(ref o);
// This will fail if `MethodName` has set the parameter value to a non-null
// non-string reference
c = (string) o;
Here's the relevant bit of the C# 3.0 spec, section 10.6.1.2 (emphasis mine):
When a formal parameter is a reference parameter, the corresponding argument in a method invocation must consist of the keyword ref followed by a variable-reference (§5.3.3) of the same type as the formal parameter. A variable must be definitely assigned before it can be passed as a reference parameter.
Does
MethodName(ref c);
not work?
精彩评论