简体   繁体   English

c#类作用域和对象创建

[英]c# class scope, and object creation

cant quite understand how class work 无法完全理解班级的工作方式

 class Class1{
             private int a;
                 for(a=0;a<10;a++){}
// how can a be out of scope?


             }

and why i can do this 以及为什么我可以做到这一点

class Class1{
             private int a;
             void tera()
              {
               private string aiha="lk"; //commenting this out ,makes it work why??
               for(a=0;a<10;a++){}
               }
             }

1st part : can a class have only methods and fields? 第一部分:一个类只能有方法和字段吗? why? 为什么?

2nd part: cant methods have declarations? 第二部分:不能有声明的方法?

i know this might be a poor explanation but i cant wrap my head around . 我知道这可能是一个不好的解释,但我不能把头缠住。

For the first part, you haven't defined a method name so it wont work, you can't place the method's body inside a class without declaring a method. 对于第一部分,您尚未定义方法名称,因此它不会起作用,也无法在不声明方法的情况下将方法的主体放置在类中。

class Class1{
      private int a = 0;
      void Example() {
         for(a=0;a<10;a++){}
       }

             }

Would work 会工作

For the second part, it wouldn't make sense as variable is only available inside the method's scope so its meaningless to give it a modifier. 对于第二部分,这是没有意义的,因为变量仅在方法的范围内可用,因此给它修饰符毫无意义。

You can read more about classes here but basically its a group of members and methods that are usually gonna be used every time you create an instance of that class. 您可以在此处了解有关类的更多信息但基本上,它是每次创建该类的实例时通常都会使用的一组成员和方法。

1st. 1。

(Classes are basic constructs of .NET Framework.) (类是.NET Framework的基本构造。)

Because it's object oriented it can only contain MEMBERS like methods, fields, constants, properties, and events as single units . 因为它是面向对象只能包含类似方法,字段,常量,属性和事件作为单个会员单位。 (note: also members must be declared within a type). (注意:成员也必须在类型内声明)。

2nd 第2

In C# there are no global variables or methods as there are in some other languages. 在C#中,没有其他某些语言中的全局变量或方法。

and i think since c# considers a method as a single object you cannot try give different access to its variables, it will think you are trying to create another member for the class. 而且我认为由于c#将方法视为单个对象,因此您不能尝试对其变量进行不同的访问,它会认为您正在尝试为该类创建另一个成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM