2013-04-22 20 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

相關問題