简体   繁体   English

从对象中删除访问器

[英]Removing Accessors from an Object

Give the following class: 提供以下课程:

public Person
{
 public string Name {get; set;}
 public string Age {get; set; }
}

If I wanted to then Return a IList is there anyway to return the List will all the Functionality of an IList but with the setters removed? 如果我想然后返回一个IList,那么无论如何返回列表将IList的所有功能但删除了setter? Possibly with an extension method to remove the setters. 可能使用扩展方法来删除setter。 I would Imagine you would have to use reflection but is this the only way that this could be done? 我想你会不得不使用反射,但这是唯一能做到这一点的方法吗? Would it be feasible from a speed/implementation point of view. 从速度/实施的角度来看是否可行。

I was just wondering how this could be done, it is not an actual design. 我只是想知道如何做到这一点,它不是一个真正的设计。 And I am aware of just returning an IEnumerable, or IEnumerable with a skip or yield that would solve for this problem. 我知道只返回一个IEnumerable或IEnumerable,其中包含一个可以解决此问题的跳过或产量。

Thanks 谢谢

with the setters removed from the Person class? 从Person类中删除setter? create 创建

IReadonlyPerson
{
  string Name { get; }
  string Age { get; }
}

have Person implement it (it already does), then return a IList. 让Person实现它(它已经),然后返回一个IList。 if you are talking about the mutability of the IList look at @RPM1984's answer. 如果你在谈论IList的可变性,请看@ RPM1984的答案。

为什么不返回ReadOnlyCollection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM