2013-04-22 57 views
2

想象一下,有3个项目。 一个库和2个可执行文件。C#代码设计:1个库,2个项目使用它(但一个只读)

这两个程序都使用该库。 项目1,在那里创建许多类的实例,用一个序列化程序保存它们。 项目2载入它们,但不应对它们进行任何更改。

因此,它应该是只读的项目2,但项目1应该有充分的权限。 我该如何设计?

比方说,有这个类在库:

public string Name { get; private set;} 
public int Age { get; private set;} 

public Person(string Name, int Age) 
{ 
    this.Name = Name; 
    this.Age = Age; 
} 

这将是完美的项目2个,谁使用它作为一个只读的。

但是对于项目1非常讨厌,因为只要改变类中的一个属性,就必须创建一个新的实例。有2个属性时不烦人,但有10个属性时很烦人。 当这些值是常量时,项目2甚至会很高兴。

什么是最好的设计方法?

回答

2

条件编译能做到这一点,只需在Visual Studio中新建的配置和使用条件编译符号,然后包所有可写的语句,以便他们例如:

public string Name { 
    get; 
#if WriteSupport 
    private set; 
#endif 
} 
public int Age { 
    get; 
#if WriteSupport 
    private set; 
#endif 
} 

public Person(string Name, int Age) 
{ 
    this.Name = Name; 
    this.Age = Age; 
} 
+0

哇,这真棒,完美的作品:) – 2013-04-22 18:39:33

3

接口是做这种事的方法。

public IPerson 
{ 
    string Name { get; } 
    int Age { get; } 
} 

在PROJECT1:

public class Person : IPerson 
{ 
    public string Name { get; set;} 
    public int Age { get; set;} 

    public Person(string name, int age) 
    { 
     this.Name = name; 
     this.Age = age; 
    } 
} 

Project2中:

public class Person : IPerson 
{ 
    public readonly string _name; 
    public string Name { get { return _name; } } 

    private readonly int _age; 
    public int Age { get { return _age; } } 

    public Person(string name, int age) 
    { 
     this._name = name; 
     this._age = age; 
    } 
} 

注意,真正的不可变类使用只读领域,而不是私人的制定者。
私有setter允许实例在创建后修改其状态,因此它不是一个真正不可变的实例。
而reaonly字段只能在构造函数中设置。

然后你就可以拥有相同的方法,通过扩展共享:

public static class PersonExtensions 
{ 
    public static string WhoAreYou(this IPerson person) 
    { 
     return "My name is " + person.Name + " and I'm " + person.Age + " years old."; 
    } 
} 
+0

看起来不错:)我有这些类在库中,所以创建一个接口和2个类在那里使用它? – 2013-04-22 16:45:29

+0

这真的取决于你的需求。这两个类可以在同一个项目中,并且名称不同,或者只有界面应该位于库中,每个项目中的每个类都可以。这取决于你和你的业务逻辑。 – 2013-04-22 16:46:36

相关问题