本文介绍了C# 中 (MyType)SomeObj.Property1 和 (MyType)(SomeObj.Property1) 之间的内部区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常蹩脚的问题,但我在 C# 规范中没有找到关于圆括号的参考.如果该问题的答案很明显,请指出我的规范或 msdn.

It's probably very lame question, but I found no references in C# specification about round brackets. Please point me to spec or msdn if answer on that question will be obvious.

C# 中 (MyType)SomeObj.Property1 和 (MyType)(SomeObj.Property1) 的内在区别是什么?

What is the inner difference between (MyType)SomeObj.Property1 and (MyType)(SomeObj.Property1) in C# ?

AFAIK,在第一种情况下 ( (x)SomeObj.Property1 cast ) - 它将是具体类型 (MyType) 到 Property1 的引用.在第二种情况下,此类引用将执行 get accessor SomeObj.get_Property1.如果 get 访问器有任何副作用(并且通常 - 确实有副作用),它最终可能会导致细微的错误

AFAIK, in first case ( (x)SomeObj.Property1 cast ) - it will be the reference of concrete type (MyType) to Property1. In second case, such reference will execute get accessor SomeObj.get_Property1.And it eventually could lead to subtle errors if get accessor have any side effects (and its often - do have ones)

有人能指点我确切的文档,其中指定了这种行为吗?

Could anyone point me to exact documentation where such behaviour specified ?

更新:感谢您的指点.我对这个愚蠢的问题深表歉意 - 在发布这个问题后,我在我摆弄的示例中发现了一个错字,因此意识到第二种情况的行为不是基于我试图编译的代码,而是基于以前编译的完全不同的代码.所以我的问题最初是基于我自己的失明...

Updated: Thank you for pointing. And I deeply apologize about such dumb question - after posting this question, I found a typo in example I fiddle with and thus realized that second case behaviour was not based on code I tried to compile, but on previously compiled completely different code. So my question was initially based on my own blindness ...

推荐答案

它们是等效的.这是由 C# 语言中的运算符优先级规则决定的,C# 语言规范中的第 7.2.1 章:

They are equivalent. This is determined by the operator precedence rules in the C# language, chapter 7.2.1 in the C# Language Specification:

. 运算符位于此列表的顶部,转换运算符位于列表中的第二个.. 运算符胜出".如果您需要强制转换,您将使用括号,因为 Property1 是 MyType 类的一个属性:

The . operator is at the top in this list, the cast operator is the 2nd in the list. The . operator "wins". You will have use parentheses if you need the cast because Property1 is a property of the MyType class:

 ((MyType)SomeObj).Property1

这篇关于C# 中 (MyType)SomeObj.Property1 和 (MyType)(SomeObj.Property1) 之间的内部区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 00:27