问题描述
以下程序输出False而不是True。
使用System;
命名空间测试
{
public struct V
{
public bool booleanV;
public void setBoolean(bool _value)
{
booleanV = _value;
}
}
公共舱C
{
public readonly V Value;
}
公共类StructBug
{
static public void Main(string [] args)
{
C c = new C();
c.Value.setBoolean(true);
Console.WriteLine(c.Value。 booleanV);
Console.Read();
}
}
}
这是正确的。这是程序员的错误,而不是编译器错误。
调查struct和class之间的区别。
-
确实应该。
来自ECMA C#规范,第14.5.4节,会员访问:
(仅适用部分):
EI表单的成员访问权限,其中E是主要表达式或
预定义类型,我是一个标识符,被评估并分类为
如下:
如果E是属性访问,索引器访问,变量或值,其类型为
为T,而I中的成员查找(第14.3节)产生匹配,
然后对EI进行评估并分类如下:
如果T是类类型,我确定该类的实例字段 -
类型:
[...]
否则,如果该字段是只读的,并且引用发生在
声明字段的类的实例构造函数,然后是
t结果是一个值,即对象中字段I的值
由E引用。
因此,由于它是一个只读字段,结果表达式
c.Value是c.Value的值,而不是变量。更改
中的数据该值不会改变c.Value中的数据,因为V是值类型。
-
Jon Skeet - < sk *** @ pobox.com>
如果回复小组,请不要给我发邮件
您还将得到一个如果编写更明显的编译器错误
操作:c.Value.booleanV = true;
对结构字段使用set方法是相当天真的我不得不承认...也许下一个
版本的C#编译器可以检查一下这个问题吗?
偷偷摸摸进入C#程序b $ b -
The following program outputs False rather than True.
using System;
namespace Test
{
public struct V
{
public bool booleanV;
public void setBoolean(bool _value)
{
booleanV = _value;
}
}
public class C
{
public readonly V Value;
}
public class StructBug
{
static public void Main(string[] args)
{
C c = new C();
c.Value.setBoolean(true);
Console.WriteLine(c.Value.booleanV);
Console.Read();
}
}
}
And that is correct. It''s a programmer bug, not a compiler bug.
Investigate the difference between struct and class.
--
http://www.kynosarges.de
And indeed it should.
From the ECMA C# spec, section 14.5.4, Member Access:
(applicable sections only):
A member-access of the form E.I, where E is a primary-expression or a
predefined-type and I is an identifier, is evaluated and classified as
follows:
If E is a property access, indexer access, variable, or value, the type
of which is T, and a member lookup (§14.3) of I in T produces a match,
then E.I is evaluated and classified as follows:
If T is a class-type and I identifies an instance field of that class-
type:
[...]
Otherwise, if the field is readonly and the reference occurs outside an
instance constructor of the class in which the field is declared, then
the result is a value, namely the value of the field I in the object
referenced by E.
So, due to it being a read-only field, the result of the expression
c.Value is the value of c.Value, not a variable. Changing the data in
that value doesn''t change the data in c.Value, as V is a value type.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
You will also get a compiler error if you write the more obvious
operation: c.Value.booleanV = true;
Using a set method for a struct field is a rather ingenuous method to
sneak bugs into a C# program, I have to admit... maybe the next
version of the C# compiler could check for that?
--
http://www.kynosarges.de
这篇关于C#编译器bug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!