[C#]为什么我只能从派生类的构造函数中访问基类字段? [英] [C#] why I can access base class fields only from the constructor of the derived class ?

查看:89
本文介绍了[C#]为什么我只能从派生类的构造函数中访问基类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这段代码是如何工作的:



Im wondering how this code is working:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp_Practicing
{
    class Parent
    {
        public string name;
        
        public Parent()
        {
            Console.WriteLine("Hello from the parent constructor");
        }
    }

    class Child : Parent
    {
        public Child()
        {
            Console.WriteLine("Hello from the child constructor"); 
            name = "Bob";
            Console.WriteLine("My name is: {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Child c = new Child();
        }
    }
}





如果我使用this.name也会发生同样的事情(但是它的工作方式不是关键字this仅仅指向(在我的例子中)成员中的成员子类???)





但是这段代码不起作用:



Also the same is happening if i use this.name (but how its working isn't the keyword "this" refering to the members ONLY in the (in my example the) Child class ???)


But this code wont work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp_Practicing
{
    class Parent
    {
        public string name;
        
        public Parent()
        {
            Console.WriteLine("Hello from the Parent constructor");
        }
    }

    class Child : Parent
    {
        name = "Bob"; 
    }

    class Program
    {
        static void Main(string[] args)
        {
            Child c = new Child();
        }
    }
}





这里的问题是为什么它无效?



我尝试了什么:



在CodeProject.com上提出问题因为当它发生在我身上时我感到非常困惑,我无法理解这段代码究竟发生了什么。



And here the question is WHY its not working ?

What I have tried:

Asking question here in CodeProject.com because I got very confused when it happened to me and I cant understand what exactly is happening with this code.

推荐答案

第一个例子有效,因为Child是从Parent派生的,所以它拥有Parent的所有属性,包括name变量。第二个例子不起作用,因为它是无效的c#。一个类可以直接包含变量声明或函数,它不能直接包含代码,代码需要在某些东西中(在工作示例中它是在构造函数中)。这可以工作



The first example works because Child is derived from Parent so it has all of the properties of Parent, including the "name" variable. The second example doesn't work because it is invalid c#. A class can directly contain variable declarations or functions, it can't directly contain code, the code needs to be "in" something (in the working example it is in the constructor). This would work though

class Child : Parent
{
    public void MyFunction()
    {
        name = "Bob";
    }
}


这篇关于[C#]为什么我只能从派生类的构造函数中访问基类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆