C#为什么偏方法使用参考,但不能跑? [英] C# Why can partial methods use ref, but not out?

查看:103
本文介绍了C#为什么偏方法使用参考,但不能跑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

漂亮的直线前进。 MSDN指出,你可以使用参考,但不能出偏的方法。我只是好奇,到为什么?这是我的理解是,当代码被编译,谐音被合并,那么什么是与限制?是否有更多的部分不仅仅是使代码文件清理和组织(即美化包)

Pretty straight forward. MSDN states that you can use ref, but not out for partial methods. I'm just curious as to the why? It was my understanding that when code is compiled, the partials are merged, so what is up with the restriction? Is there more to partial than just making code files cleaner and organized (i.e. eyecandy)?

参考:<?一HREF =htt​​p://msdn.microsoft.com/en-us/library/wa80x488.aspx> MSDN文章 - 分部方法可以的ref 但不是参数。

Reference: MSDN Article - "Partial methods can have ref but not out parameters."

推荐答案

您有必要考虑到如果部分方法未实现会发生什么。

You got to consider what happens if the partial method isn't implemented.

会发生什么事,然后就是该方法的所有调用只是剥离出来,就好像它们从来没有发生过。

What happens then is that all calls to the method is just stripped out as though they never happened.

因此,对于一个方法使用了,它是这样的:

So for a method using out, it would look like this:

stream s;
GetStream(out s);
s.Write(...);

和,就好像它说,这编译

and be compiled as though it said this:

stream s;
s.Write(...);

这代码是不允许的,因为取值有尚未初始化。该变量将由时间来初始化的保证你试图调用方法,它被捆绑与调用 GetStream

This code is not allowed because s has not been initialized. The guarantee that the variable would be initialized by the time you try to call the Write method on it was tied up with the call to GetStream.

这是方法返回的数据相同。因为如果你还没有实施的部分方法把整个方法的调用是不编译,你需要考虑你能不能做,仍然留下调用它有效的代码。在方面出和返回值,它让调用代码无效或不完整的潜力,所以这是不允许的。

It is the same with methods returning data. Since the entire method call is just not compiled if you haven't implemented the partial method, you need to consider what you can and cannot do and still leave the code that calls it valid. In terms of out and return values, it has the potential of leaving the calling code invalid or incomplete, so it is not allowed.

至于 REF ,即有效的,因为在初始化已被调用代码照顾:

As for ref, that is valid since the initialization has been taken care of by the calling code:

stream s = null;
GetStream(ref s); // may be stripped out
if (s != null)
    s.Write(...);

这篇关于C#为什么偏方法使用参考,但不能跑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆