C # Write protection members in the class (invite everyone to make a picture)

Source: Internet
Author: User

Assume that I have a class library Lib that provides a class ClassA external service. ClassA has several read-only attributes, such as PropA and PropB. External callers cannot perform write operations on PropA and PropB in ClassA, so I can define this as follows: copy the code namespace Lib {public class ClassA {public string PropA {get; private set;} public string PropB {get; private set ;}}} copy the code, but the ClassB In the Lib library needs to write the PropA attribute in the ClassA. What should I do? If the set of open ClassA is public, the logic is broken. My approach is to define an interface IMemberSetter to write data to members. Copy the code namespace Lib {interface IMemberSetter {void SetMember (string member, object value) ;}} and then implement this interface in ClassA. Modify the Code as follows: copy the code namespace Lib {public class ClassA: IMemberSetter {private string propA; private string propB; public string PropA {get {return propA ;}} public string PropB {get {return propB;} void IMemberSetter. setMember (string member, object value) {switch (member) {case "Pr OpA ": this. propA = (string) value; break; case "PropB": this. propB = (string) value; break ;}}} copy the code. When ClassB wants to modify an attribute in ClassA, it only needs to convert ClassA to the IMemberSetter interface for access and then call the SetMember method. This idea is expected to be made by everyone, because if feasible, I will integrate it into the next project.

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.