开发者

is the below a good approach to returning a safe list enumerator?

 public class Foo{
        public string Prop1 {get;set;}
        public string Prop2 {get;set;}

        public Foo(Foo source) {
            this.Prop1 = source.Prop1;
            this.Prop2 = source.Prop2;
        }
    }

    public class Main
    {
        private List<Foo> items = new List<Foo>();

        public IEnumerable<Foo> GetItems() {
            foreach (Foo foo in items) {
                yield return new Foo(foo);
            }
      开发者_Go百科  }
    }


It depends on what you call safe. If the calling objects are just going to read information from foo. Instead of:

public IEnumerable<Foo> GetItems() {
            foreach (Foo foo in items) {
                yield return new Foo(foo);
            }

why not just do:

public IEnumerable<Foo> GetItems() {
            foreach (Foo foo in items) {
                yield return foo;
            }

If you are attempting to prevent the calling object from modifying the original foo, what you have done will work.

You could also just set foo to be immutable, and you won't have to worry about making sure you copy all the properties correctly etc. That way you won't have to create a new object each time you return it through the enumerator.

Post by eric lippert on immutability:
http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx

Other link on immutability:
http://codebetter.com/blogs/patricksmacchia/archive/2008/01/13/immutable-types-understand-them-and-use-them.aspx


Disclaimer: I know Java, but have very little experience with C#

If you are trying to create a list of copies so that the original list elements remain "immutable", and want to make this as general as possible, maybe you should investigate cloning, or, more precisely, deep-copying

Otherwise just creating a new instance of the Item foo will not necessarily ensure you have a perfectly initialized copy?


OK so it seems to be clear that you are looking for an immutable iterator. This works but isn't exactly efficient. You could try making your class like this:

public class Foo {
    public string Prop1 { get; private set;}
    public string Prop2 { get; private set;}

    public Foo(string prop1, string prop2) {
        this.Prop1 = prop1;
        this.Prop2 = prop2;
    }
}

It isn't exactly immutable but for most intents it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜