[英]How can I return a ReadOnly object class with mutable properties while allowing write access
我有很多類,它們具有標准設置和獲取方法。 我的問題是,許多這些set方法不應該是從持有的對象類的外部調用。 我不確定是否有任何模式或C#缺少更好的詞-操作會使其變得更容易。
參考下面的代碼,有許多類似於SecureSite的類,控制器應該能夠調用這些類或訪問變量以修改SecureSite(以及其他類似的類)。 但是,當用戶要求查看SecureSite等時,他們應該不能更改此設置。
據我有限的知識和我對該站點上類似問題的回答,主要問題似乎是由於List<String> AccessHistory
變量導致Write_SecureSite無法完全不可變。 所以,我想出的東西看起來就像牛頭犬的后部一樣丑陋,而且也很雜亂。 本質上,SecureSite類有一個Write版本,其中包含一個類,該類返回SecureSite類的只讀版本。
因此,我是否在C#中缺少某種魔術,這將使這一切變得如此容易?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReadOnlyExample {
public class Write_SecureSite {
private List<String> mAccessHistory;
public List<String> AccessHistory {
get {
return mAccessHistory;
}
}
public SecureSite ReadOnly {
get {
return new SecureSite(this);
}
}
public class SecureSite {
public SecureSite(Write_SecureSite aParent) {
AccessHistory=aParent.AccessHistory;
}
public IEnumerable<String> AccessHistory;
}
}
public static class Controller {
private static Write_SecureSite SimpleSecureSite=new Write_SecureSite();
public static Write_SecureSite.SecureSite Login(String MyLogin) {
SimpleSecureSite.AccessHistory.Add(MyLogin);
return SimpleSecureSite.ReadOnly;
}
public static Write_SecureSite.SecureSite Details() {
return SimpleSecureSite.ReadOnly;
}
}
public static class User {
public static void Miscellaneous() {
Controller.Login("Me");
Write_SecureSite.SecureSite SecureSite=Controller.Details();
//Not going to happen.
SecureSite.AccessHistory.Add("Me2");
//No problem.
foreach(String AccessedBy in SecureSite.AccessHistory) {
Console.Out.WriteLine("Accessed By: "+AccessedBy);
}
}
}
}
我建議使用接口:
public interface IReadSecureSite
{
IEnumerable<String> AccessHistory { get; }
}
class Write_SecureSite : IReadSecureSite
{
public IList<String> AccessHistoryList { get; private set; }
public Write_SecureSite()
{
AccessHistoryList = new List<string>();
}
public IEnumerable<String> AccessHistory {
get {
return AccessHistoryList;
}
}
}
public class Controller
{
private Write_SecureSite sec= new Write_SecureSite();
public IReadSecureSite Login(string user)
{
return sec;
}
}
...
Controller ctrl = new Controller();
IReadSecureSite read = ctrl.Login("me");
foreach(string user in read.AccessHistory)
{
}
這並不是一個答案,而是一個研究方向。 我也在不可變類上掙扎
到目前為止,我使用構造函數設置只讀私有變量,使用方法在內部更新列表,而不是將其公開為公共屬性:即。 使用公共虛空添加(字符串itemToAdd)
我正在閱讀Petricek和Skeet撰寫的名為“ 真實世界的函數式編程 ”的書,它正在幫助我朝着您所討論的方向前進
這是同一作者的一個小教程,介紹了一些基本概念: http : //msdn.microsoft.com/zh-cn/library/hh297108.aspx
希望這個對你有幫助
更新:我可能應該更清楚一些:我希望將您指向更具功能性的觀點,而不是重寫您在問題中列出的類-我的道歉(刪除的示例)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.