C#财产和ref参数,为什么没有糖吗? [英] C# property and ref parameter, why no sugar?

查看:146
本文介绍了C#财产和ref参数,为什么没有糖吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是碰到这种错误信息跑在C#

I just ran across this error message while working in C#

属性或索引器不可能会作为传出或引用参数传递

A property or indexer may not be passed as an out or ref parameter

我知道什么造成这一点,并没有创造正确类型的局部变量的快速解决方案,调用它的函数作为退出 / REF 参数,然后分配给它回属性:

I known what caused this and did the quick solution of creating a local variable of the correct type, calling the function with it as the out/ref parameter and then assigning it back to the property:

RefFn(ref obj.prop);

变成

{
    var t = obj.prop;
    RefFn(ref t);
    obj.prop = t;
}

显然,如果物业不支持获取和在当前上下文中设置此会失败。

Clearly this would fail if the property doesn't support get and set in the current context.

为什么不C#只是为我做的?

Why doesn't C# just do that for me?

在这里我能想到的,其中可能会导致问题的唯一情况是:

The only cases where I can think of where this might cause problems are:


  • 线程

  • 例外

有关线程时写​​发生(在函数调用的函数调用与后),这种转变影响,但我有些怀疑任何code才是最重要的,当它打破会得到一点同情。

For threading that transformation affects when the writes happen (after the function call vs. in the function call), but I rather suspect any code that counts on that would get little sympathy when it breaks.

有关例外,值得关注的是,如果函数分配给几个 REF之一参数不是抛出,会发生什么?任何平凡解将导致全或无的参数被分配到一定的时候应该是有些不应该。再次,我不认为这会被使用的语言的支持。

For exceptions, the concern would be; what happens if the function assigns to one of several ref parameters than throws? Any trivial solution would result in all or none of the parameters being assigned to when some should be and some should not be. Again I don't think this would be supported use of the language.

请注意:我明白了,为什么会产生这个错误信息的机制。我正在寻找的是为什么C#不自动实现琐碎的解决方法的基本原理。

Note: I understand the mechanics of why this error messages is generated. What I'm looking for is the rationale for why C# doesn't automatically implement the trivial workaround.

推荐答案

只是为了信息,C#4.0的将会的有一些的的这种糖,但只有当调用互操作方法 - 部分是由于在这种情况下裁判的绝对倾向。我还没有足够多的测试它(在CTP);我们必须看看它是如何平移出...

Just for info, C# 4.0 will have something like this sugar, but only when calling interop methods - partly due to the sheer propensity of ref in this scenario. I haven't tested it much (in the CTP); we'll have to see how it pans out...

这篇关于C#财产和ref参数,为什么没有糖吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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