简体   繁体   English

在属性内为属性赋值

[英]Assign property a value inside a class

I've quite a simple question. 我有一个非常简单的问题。 Why can't you assign property a value outside of a method, like shown below? 为什么不能在属性之外为属性赋值,如下所示? Whats the difference between doing it inside a method and outside a method? 在方法内部和方法外部进行区别是什么?
Please see below: 请看下面:

在此输入图像描述

Edit: 编辑:

Below is what I was trying to do, hence the question above. 以下是我试图做的事情,因此上面的问题。

在此输入图像描述

Anything inside of a classes root scope is just part of the class definition. 类根范围内的任何内容都只是类定义的一部分。 The class definition defines what properties the object has, what methods can be invoked on it, the ways to construct the object, etc. 类定义定义了对象具有哪些属性,可以在其上调用哪些方法,构造对象的方法等。

Putting an actual statement here doesn't make any sense; 在这里提出一个实际的陈述没有任何意义; when would it run? 什么时候会跑? Actual execution of code is not part of a class definition. 代码的实际执行不是类定义的一部分。

Thus, all statements must reside in a method, since methods are the only things that actually execute statements. 因此,所有语句都必须驻留在方法中,因为方法是实际执行语句的唯一方法。

You can exectue code when the class is created. 您可以在创建类时执行代码。 Use a constructor for this. 为此使用构造函数。 It looks like a method but has no return type and its name is the same as the class name: 它看起来像一个方法,但没有返回类型,其名称与类名相同:

public class SubClass : BaseClass
{
    public SubClass()
    {
        Build = "Hello"; // Build must be either public or protected in the base class.
        // SubClass inherits Build, therfore no "base." is required.
    }

    // Other methods to go here
}

If the base class has a constructor having parameters, you must pass those the base class' constructor: 如果基类具有带参数的构造函数,则必须传递基类的构造函数:

public class BaseClass
{
    public BaseClass(string build)
    {
        Build = build;
    }

    public string Build { get; private set; }
}

public class SubClass : BaseClass
{
    public SubClass()
      : base("Hello")  // Calls the base class' constructor with "Hello"
    {
    }
}

Now you can call: 现在你可以打电话:

var baseClass = new BaseClass("Hello");
// or
var subClass = new SubClass();

Both assign "Hello" to Build . 两者都为Build分配"Hello"

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

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