简体   繁体   English

ref对象参数的方法

[英]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";

MethodName(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. 当方法具有ref参数时,参数类型必须与参数类型完全匹配。 Suppose MethodName were implemented like this: 假设MethodName是这样实现的:

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 ? 如果你能用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. 它试图将对普通System.Object的引用写入System.String类型的变量,从而破坏类型安全性。

So, you need to have a variable of type object . 所以,你需要一个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. 你可以这样做,如klausbyskov的回答所示,但请注意,该值不会被复制回原始变量。 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): 这是C#3.0规范的相关部分,第10.6.1.2节(强调我的):

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 . 当形式参数是引用参数时,方法调用中的相应参数必须包含关键字ref,后跟与形式参数相同类型的变量引用(第5.3.3节)。 A variable must be definitely assigned before it can be passed as a reference parameter. 必须明确赋值变量才能将其作为参考参数传递。

Does 是否

MethodName(ref c);

not work? 不行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM