Access modifiers in C # keywords protected

Source: Internet
Author: User

Https://msdn.microsoft.com/zh-cn/library/bcd5672a.aspx

The official statement is that the protected keyword is a member access modifier. A protected member is accessible within it class and by derived class instances.

The protected keyword is a member access modifier. A member of a protected, a protected member, that is accessible by an instance of its derived class in the class in which it resides.

An introduction to the accessibility level:

Https://msdn.microsoft.com/zh-cn/library/ba0a1yw2.aspx

Protected:access is limited to the containing class or types derived from the containing class.

Protected keyword: Access can only be accessed by the containing class, or from a class that contains the Member's class.

The place of doubt: wrong point of view I thought that as long as it was an instance of a derived class, you could access the protected member .

Http://blogs.msdn.com/b/ericlippert/archive/2005/11/09/why-can-t-i-access-a-protected-member-from-a-derived-class.aspx

Class Ungulate {

protected virtual void Eat () {/* whatever */}
}

Class Zebra:ungulate {
protected override void Eat () {/* whatever */}
}

Class Giraffe:ungulate {
public static void Feedthem () {
Giraffe G1 = new Giraffe ();
ungulate g2 = new Zebra();
G1. Eat (); Fine
G2. Eat (); Compile-time Error "Cannot access protected member"
}
}

We can call ungulate.eat legally from Giraffe,

But we can ' t call the protected method zebra.eat from anything except zebra or a subclass of zebra.

Since The compiler cannot determine from the static analysis that we is not in this illegal situation, it must flag it as Being illegal.

Access modifiers in C # keywords protected

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.