zoukankan      html  css  js  c++  java
  • 设计模式之读写装饰

    今天有人问我如下代码:

    1 public class UserInformation
    2     {
    3         public string Name { get; set; }
    4 
    5         public uint Age { get; internal set; }
    6     }

    UserInformation.Age 这个代码在A程序集里面可以,但是在B程序集里面却无法使用了,如何解决?

    其实这个问题本质跟设计模式有关系,internal 在C#中是程序集内可访问的修饰符.  

    因此我想到了第一种方案:

     1 public class UserInformation
     2     {
     3         public string Name { get; internal set; }
     4 
     5         public uint Age { get; set; }
     6 
     7         public void SetName(string name)
     8         {
     9             Name = name;
    10         }
    11     }

    有点儿Java的风格,并不喜欢。考虑了第二中方案:

     
     1 public interface IInformation
     2     {
     3         string Name { get; }
     4 
     5         uint Age { get; }
     6     }
     7 
     8     public interface IMutableInformation : IInformation
     9     {
    10         new string Name { set; }
    11 
    12         new uint Age { set; }
    13     }

    那么,实体类的实现如下:

     1  public class UserInformation : IInformation , IMutableInformation
     2     {
     3         private string _Name = string.Empty;
     4         private uint _Age = default(uint);
     5 
     6         public string Name { get { return _Name; } }
     7 
     8         public uint Age { get { return _Age; } }
     9 
    10         string IMutableInformation.Name
    11         {
    12             set { _Name = value; }
    13         }
    14 
    15         uint IMutableInformation.Age
    16         {
    17             set { _Age = value; }
    18         }
    19     }

    下面,我就开始调用它了:

     1  class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5 
     6             A.UserInformation information = new A.UserInformation();
     7             A.IMutableInformation mutableInformation = information;
     8             mutableInformation.Name = "张三丰";
     9             mutableInformation.Age = 102;
    10 
    11             Console.WriteLine(information.Name);
    12             Console.WriteLine(information.Age);
    13 
    14             // information.Name = "张三丰"; // 这样,此处编译的时候会出错,你需要用【IMutableInformation】接口 给【A.UserInformation】赋值.
    15 
    16             Console.ReadLine();
    17         }
    18     }

    就介绍到这里了....

  • 相关阅读:
    jquery中简易tab切换
    网页中用哪种空链接
    php中each()与list()函数
    转:const“变量”、define的常量和static 变量
    php错误收集
    php基础小知识
    初学深度学习(TensorFlow框架的心得and经验总结)自用环境的总结
    Python扩展模块——调用WindowsAPI(pywin32的简单使用)
    Python扩展模块——selenium的使用(定位、下载文件等)
    Python扩展模块——自动化(testlinkAPI的使用)
  • 原文地址:https://www.cnblogs.com/blakebook/p/5871345.html
Copyright © 2011-2022 走看看