开发者

Why must initialization value of field members be determinable at compile time?

1) Why must initialization value开发者_高级运维 of field members be determinable at compile time?

2) But if the initialization value needs to be determined at compile time, then why am I able to initialize a A.b field using a reference to an object:

class A
{
     B b = new B(); 
}

class B {}

Thank you


I'm a bit confused; there is no such rule for fields. In particular, fields are explicitly initialized anyway - either by your code, or to the type's default. The only corner-case is explit struct field initialization, in which all fields must be assigned before the struct is considered complete.

I wonder if you are talking about "definite assignment" of variables within methods; i.e.

void Foo() {
    int i;
    Console.WriteLine(i); // not valid; i not assigned
    i = 1;
    Console.WriteLine(i); // would be value
}

This is so that for method variables the values never suffer from random values picked up from the stack. Actually, there is an IL marked that means that locals are wiped - and IIRC the C# compiler includes this marker anyway... but the language spec says method variables must be definitely assigned.


In the case of you example, that field-initialization essentially becomes part of the common constructor code. But you'd never notice it.


1) Why must initialization value of field members be determinable at compile time?

It mustn't. Why do you think that ?


If you mean this part of the book Illustrated C# 2008, then it is in the section talking about const fields. The compiler may replace the use of a const field with the value of the const field, so the initialiser for the field must be constant.

The field in your original post is not a const. Therefore the restriction does not apply to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜