C# 属性和 ref 参数,为什么不加糖? [英] C# property and ref parameter, why no sugar?

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

问题描述

我在 C# 中工作时遇到了这个错误消息

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

属性或索引器不能作为 out 或 ref 参数传递

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

我知道是什么导致了这种情况,并做了一个快速的解决方案,即创建一个正确类型的局部变量,用它作为 out/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;
}

显然,如果该属性在当前上下文中不支持 get 和 set,这将失败.

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:

  • 线程
  • 例外

对于线程,转换会影响写入发生的时间(在函数调用之后与在函数调用中),但我更怀疑任何依赖于它的代码在它中断时都不会得到同情.

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 参数之一而不是 throws,会发生什么?任何微不足道的解决方案都会导致所有或不分配任何参数,而有些应该是,有些则不应该.同样,我不认为这会支持使用该语言.

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 类似这种糖,但仅在调用互操作方法时- 部分原因是在这种情况下 ref 的绝对倾向.我没有对其进行太多测试(在 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天全站免登陆