开发者

Why and when there are things I can not do in CLASS SCOPE in C#?

开发者 https://www.devze.com 2023-01-08 06:47 出处:网络
well... I\'m confused about what can I do and what I can\'t do in CLASS SCOPE. For example =========================

well... I'm confused about what can I do and what I can't do in CLASS SCOPE.

For example

=========================

class myclass
{


  int myint = 0;

  myint = 5; *// this doesnt work. Intellisense doesn't letme work with myint... why?*

  void method()
  {
    myint = 5; *//this works. but why inside a method?*
  } 
}

==================================

class class1
{ 
 public int myint;
}

class class2
{
  class1 Z = new class1();

  Z.myint = 5; *//this doesnt work. like Z doesnt exists for intellisense*

 void method()
  {
开发者_如何学Python    Z.myint = 5; *//this Works, but why inside a method?*
  }
}

Thats I make so many mistakes, I dont understand what works on class scope and what doesnt work.

I know that there are local varaibles and its life cycle. But I dont understand the so well the idea.


A class can only contain declarations, initializations, and methods. It cannot contain statements of its own.

class MyClass
{
    int x; // a declaration: okay
    int y = 5; // a declaration with an initialization: okay
    int GetZ() { return x + y; } // a method: okay

    x = y; // a statement: not okay
}


You can initialize a field, but you can't just have assignment statements.


You can't do the below:

class myclass
{
  int myint = 0;
  myint = 5;

Because there is nothing to do, you can only declare members and possibly set an initial value. It is nothing to do with scope. One of the reeasons you can't do it is that there is no guarantee of order, the compiler just gurantees all values will be initialised by the time the class is instantiated. That is why you also cannot do the following:

class myclass
{
  int myint = 0;
  int MyOtherInt = myint;

If you want to set the value when the class is instantiated, put it in the contructor.


Basically, when you create a class, you are not allowed to have code & assignments inside that class directly.

but as c# wants to help you, it allows you to define initial states for fields. and they are basically executed directly bevore your constructor code.

when you now want to define code inside the class. somewhere... the program would not know, when to execute. so they are forbidden.


A class definition defines its makeup, that is, the fields, properties, methods, events, etc. that it contains. The "work" is actually done inside methods.

What you seem to be confusing is the initialization of the fields of a class with the usage of those fields. You can initialize a field outside a method definition, but to use it, you need to be inside a method.


To clearly understand it and get answers on your questions you should read Jeffrey's Richter "CLR via C#, Third Edition" and C# 4.0 Language Spectification

0

精彩评论

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

关注公众号