![](/img/trans.png)
[英]Can C# (somehow) work out the type constraints itself when a generic type is passed as a generic type reference?
[英]C# - When reference type is passed using the out keyword, then can calling function code control the outer object?
在C#中,我知道在传递ref类型时,默认情况下会按值传递-值是地址,因此内部函数中对象属性的任何更改也将反映在外部对象上。 但是,将内部对象分配为null或另一个对象或创建新对象(使用new关键字)不会影响外部对象。 为了达到更高的要求,我们需要使用ref关键字通过ref传递引用类型(对象)。
这个问题是关于out关键字的。 使用out关键字传递值类型时,地址将传递给调用函数,并且任何更新也将反映给外部对象。
但是,当使用out关键字传递引用类型(例如Car类的对象)时,调用函数代码可以控制外部对象吗?
function foo(out Car x)
{
x=null //or x=new Car(); //or x.speed=0
//Will the last one (x.speed=0) reflect to outer object, where as the
//1st 2 - that is - the null or new assignments wont reflect?)
}
Car c= new Car();
c.speed=100;
foo(out c);
console.writeline(x.speed);
现在,外部对象“ c”是否指向在函数中创建的新对象?
还是我们没有使用out关键字通过ref传递的概念?
out
与ref
完全相同。 因此,它的工作方式相同,但在外观上存在一些差异:
out
参数中传递未初始化的变量(在ref
参数中,您必须传递初始化变量) c.speed=0
类的c.speed=0
之前,必须首先为其分配一个值。 Ref用于将引用传递给变量,因此您可以对其进行更改。 Out仅用于返回值,它不关心传递的对象,如果您的执行分支未在方法内部设置值或在设置值之前使用该值,则它将导致编译错误。
因此,在您的情况下,实例化c不会执行任何操作。 结果为null,并且尝试访问.speed时将获得运行时异常(我认为是c而不是x)
代码不带:
Car c;
foo(out c); //if foo doesn't set c, you get compile errors
// now c is set by foo
参考代码:
Car c=new Car();
foo(ref c);
// c was perhaps modified or set by foo
带有ref的代码无法编译:
Car c;
foo(ref c); //error because c is not instantiated
无法编译的代码:
static void foo(out string text) {
DoSomethingWith(text); //error because text is not instantiated
text="something";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.