暴露,可以在内部进行修改的只读属性在内部、属性

2023-09-07 00:52:12 作者:烟酒脏话样样在行

我要创建一个类,将众议院选举结果。我有了将解析文件,并从文件的结果返回一个结果类的静态方法的结果类。

I'm creating a class that will house election results. I have a results class that has a static method that will parse a file and return a results class with the results from the file.

我要确保只有静态方法可以修改的结果,所以我一直在使用内部修饰符(precinct.InternalCandidates)(我班的DLL以外的距离prevents实例访问的方法,对吧?)。

I want to make sure that only the static method can modify the results, so i've been using the internal modifier (Precinct.InternalCandidates) (The prevents instances of my class outside of the dll from accessing the methods, right?).

不管怎样,我需要公开的考生来说是只读列表,我的类的实例化版本,但我显然需要能够在填充过程中添加的候选人。所以,我创建了precinct类叫做precinct.Candidates暴露只读版本InternalCandidates的另一个参数

Anyway, I need to expose the candidates as a read only list to the instantiated version of my class, but I'll obviously need to be able to add candidates during the population process. So, I've created another parameter in the Precinct Class called Precinct.Candidates that exposes a read only version of InternalCandidates

下面是我想象它的工作:

Here's how I'd envision it to work:

Results r = Results.ParseResultsFile("PathToFile.txt");
r.Candidates.Add(new Candidate) // Should error here
Console.WriteLine(r.Candidates[0].Name) // Should work

下面是我为我的类存根:

Here's what I have for my class stubs:

public class Results {
  private List<Precinct> precincts = new List<Precinct>();
   public ReadOnlyCollection<Precinct> Precincts {
      get { return this.precincts.AsReadOnly(); }
  }

  public Results() {}

  public static Results ParseResultsFile(string filePath) { ... }
}

public class Precinct {
  internal List<Contest> InternalContests { get; set; }
  public ReadOnlyCollection<Contest> Contests {
    get { return this.InternalContests.AsReadOnly(); }
  }
  public Precinct {
    this.InternalContests = new List<Contest>();
  }
}

有没有更好的方式来做到这一点?

Is there a better way to accomplish this?

推荐答案

再。清理我的老问题......最后我只是我自己的滚动集合。

Again. Cleaning up my old questions... I ended up just rolling my own Collection.

摸索出美妙。

 
精彩推荐
图片推荐