设计模式之读写装饰

今天有人问我如下代码:

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     }

就介绍到这里了....

posted @ 2016-09-14 11:53  思想决定一切  阅读(214)  评论(0编辑  收藏  举报