无法访问受保护的会员?

时间:2014-12-02 05:37:49

标签: c#

我正在学习C#,我写了下面的代码,但是没有用。

受保护的成员可以通过继承该类来访问,但是在下面的代码中它不起作用可以任何人请告诉我我在哪里做错了吗?

   class ProtectedDemo
{
    protected string name;

    public void Print()
    {
        Console.WriteLine("Name is: {0}", name);
    }
}

class Demo : ProtectedDemo
{
    static void Main(string[] args)
    {
        ProtectedDemo p = new ProtectedDemo();
        Console.Write("Enter your Name:");
        p.name = Console.ReadLine(); //Here i am getting the error.
        p.Print();
        Console.ReadLine();
    }
}

3 个答案:

答案 0 :(得分:2)

来自protected (C# Reference)

  

protected关键字是成员访问修饰符。受保护的成员   可以在其类和派生类实例中访问。

因此,从此评论中可以从ProtectedDemo内或从继承类Demo

访问它

然后是他们的例子

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        A a = new A();
        B b = new B();

        // Error CS1540, because x can only be accessed by
        // classes derived from A.
        // a.x = 10; 

        // OK, because this class derives from A.
        b.x = 10;
    }
}

所以将课程改为

class Demo : ProtectedDemo
{
    static void Main(string[] args)
    {
        //ProtectedDemo p = new ProtectedDemo();
        Demo p = new Demo(); //NOTE HERE
        Console.Write("Enter your Name:");
        p.name = Console.ReadLine(); //Here i am getting the error.
        p.Print();
        Console.ReadLine();
    }
}

答案 1 :(得分:1)

受保护只能用于派生类或实际的类本身。

以下是一篇关于访问修饰符的文章:What are Access Modifiers in C#?

如果要设置它,要么将其设置为公共,要么创建一个将字符串作为参数并将其设置在那里的方法。这样的事情。

    class ProtectedDemo
    {
        protected string name;

        public void Print()
        {
            Console.WriteLine("Name is: {0}", name);
        }

        public void SetName(string newName)
        {
            name = newName;
        }
    }

    static void Main(string[] args)
    {
        ProtectedDemo p = new ProtectedDemo();
        Console.Write("Enter your Name:");
        p.SetName(Console.ReadLine()); 
        p.Print();
        Console.ReadLine();
    }

或者如果要在Deriving类上设置它。这样做

class Demo : ProtectedDemo
{
    static void Main(string[] args)
    {
        Demo test = new Demo();
        Console.Write("Enter your Name:");
        test.name = Console.ReadLine(); // create an instance of the deriving class, 
                                        // you can only access the name if you're in the current class created
        test.Print();
        Console.ReadLine();
    }
}

答案 2 :(得分:0)

  

您只能访问班级内的受保护成员或使用   继承父级的子类(Demo)上的对象   类(ProtectedDemo)。

您可以像访问它一样访问它。

Demo d = new Demo();
d.name = Console.ReadLine();