[英]Inline reference types to methods?
I am working with an API that contains a method with a reference type. 我正在使用包含引用类型方法的API。 I don't always need to pass information into the method.
我并不总是需要将信息传递给方法。 Is there some way to pass a default or null value inline?
有什么方法可以内联传递默认值或空值?
What I'm currently doing: 我目前正在做什么:
MyObject obj = null;
MyMethod(ref obj);
What I'd like to do is something like: 我想做的是这样的:
MyMethod(ref null);
I understand why this doesn't work, but it gets the point across. 我了解为什么这行不通,但却可以说明要点。
you can't modify null
. 您不能修改
null
。 parameters declared as ref
(or out
) must be named variables. 声明为
ref
(或out
)的参数必须命名为变量。 null
is a value. null
是一个值。
that is not a reference type - that is a pass by reference parameter. 不是引用类型,而是按引用传递参数。 That means
MyMethod
can modify the reference to obj
. 这意味着
MyMethod
可以修改对obj
的引用。
That API is likely expecting to give the caller something. 该API可能期望给调用者一些东西。 Carefully read the documentation to see what it expects.
仔细阅读文档以查看期望的内容。
In my best guess, the caller should always provide it a value when it is ref
. 用我的最佳猜测,当调用者是
ref
时,调用者应始终为其提供一个值。 That way the method can use it as needed. 这样,该方法可以根据需要使用它。 Otherwise, the method should have declared it as
out
. 否则,该方法应将其声明为
out
。
null
is a value... Ref keyword means that you should pass reference to some instance (which is typically just a variable) and not value. null
是一个值... Ref关键字意味着您应该将引用传递给某个实例(通常只是一个变量)而不是值。 That's why when method expects reference to a variable - it doesn't accept null
. 这就是为什么当方法期望引用一个变量时,它不接受
null
。 For example: 例如:
void A(ref string str) // expects reference not value
{
}
void A(string str) // expects value not reference
{
}
Create a second method without the parameter: 创建不带参数的第二种方法:
private void MyMethod()
{
MyObject notNeeded = null;
MyMethod(ref notNeeded);
}
Nevertheless, as the others already mentioned there seems to be something wrong in your design, if this method doesn't need the given reference all the time. 但是,正如其他人已经提到的那样,如果此方法不需要始终使用给定的引用,则您的设计似乎存在问题。 Maybe you should think about what your method is doing and maybe split it up into multiple methods.
也许您应该考虑您的方法在做什么,并且可能将其拆分为多个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.