如何设置和获得私有成员的遗产价值 [英] how to set and get value of privae members of inheritence

查看:115
本文介绍了如何设置和获得私有成员的遗产价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当成员f类声明为私有时,set和get属性如何工作????

给我一个简单的例子,可以很容易理解... thnx

when members f class declared as private then how the set and get property works????
give me ans with simple examples that could understand easily... thnx

推荐答案

当您将它们声明为私有时,只能从该类中访问它们,而不能从其中进行访问:

When you declare them as private, they can only be accessed from within that class, and no other:
public class MyBase
    {
    private string MyProp { get; set; }
    public void Method(string s) { MyProp = s; }
    public string OtherMethod() { return MyProp; }
    }
public class MyDerived : MyBase
    {
    public void SetIt()
        {
        MyProp = "hello";  // **** ERROR ****
        Method("Hello");   // OK
        }
    }

即使你从MyBase派生出一个新类,新类无法访问私有成员。为此,您可以将其声明为受保护:

Even if you derive a new class from MyBase, the new class cannot access the private members. To allow that, you can declare it as protected:

{
    protected string MyProp { get; set; }
    public void Method(string s) { MyProp = s; }
    public string OtherMethod() { return MyProp; }
    }
public class MyDerived : MyBase
    {
    public void SetIt()
        {
        MyProp = "hello";   // OK
        Method("Hello");    // OK
        }
    }



类中声明的任何内容都可以在该类中的任何位置使用,无论保护级别如何,但您可以使用私有,受保护和内部说明符限制对类外的访问。


Anything declared within a class is available anywhere within that class regardless of the protection level, but you can restrict access to it outside the class, using the private, protected and internal specifiers.

这篇关于如何设置和获得私有成员的遗产价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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