开发者

Using an array or IEnumerable for a detail class

I have this class:

public class TextFiller
{
    public HtmlText Text { get; set; }
    public string Details { get; set; }
}

What I need is to create a parent class that will consist of many TextFillers. I am wondering the best way to do this. Would it be best to do it using what I have on line a, line b or is there some better solution?

public class TextFillerParent
{
  public TextFiller[] TextFiller { get; set; }    <<< a
  public IEnumerable<TextFiller> TextFiller { get; set; }  <<< b
}

What I will be doing is storing the data in Azure so I will want to be able to serialize TextFillerParent into a JSON string. Will there be any difference if the contents of Tex开发者_JAVA技巧tFillerParent are an array of TextFiller or if I use the IEnumberable? Are there advantages in using IEnumerable?

I MUST be able to set the value of individual TextFiller. I know I can do this with an array but can I also do that if I use IEnumerable or is IEnumerable only good for sequential access?

Thank you.


You may wish to use the generics version of IList if you need to access individual items. I would recommend it over the array.

Also, using LINQ, you can get much more than sequential access from IEnumerable objects.


I'd use the IEnumerable version you say on b. It allows more control using generics and is also good for serialization.


I would declare it as an IEnumerable, IF you don't need to be able to index it. If you do, try using IList (which inherits from the generic IEnumerable).

The reason why is exactly as Will said; an array must always be an array. You can index and enumerate through it, but you cannot add to, remove from, etc without rolling your own extendo-Array code.

By contrast, using IEnumerable allows you to use anything implementing that interface, which widens the candidate field considerably; all you care about is that whatever's referenced can be enumerated, on top of whatever else the actual enumerable type can do.


Generics: public IEnumerable<TextFiller> TextFiller { get; set; }

give you a friendlier / more type safe interface for adding, removing, searching, and so on. As long as your properties (Text, Details) remain public then they'll be serializable.

You can access an individual TextFiller in the list by doing either:

var thisItem = MyList[2];

or

var thisItem = MyList.Find(AddressOf anotherObject);

Here's another post which covers some benefits of Generics over Arrays.

Generics vs. Array Lists


    var Parent = new TextFillerParent();
    Parent.TextFillers.Add(new TextFiller { ..});
    Parent.TextFillers.Add(new TextFiller { ..});

    if(Parent.TextFillers[1] != null)
    {
        var child = Parent.TextFillers[1];
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜