开发者

Parent / Child relationships in interfaces

开发者 https://www.devze.com 2022-12-08 10:11 出处:网络
If I were to have interfaces like so: public interface IAlbum { string Title { get; set; } } public interface ITrack

If I were to have interfaces like so:

public interface IAlbum
{
    string Title { get; set; }
}

public interface ITrack
{
    string Title { get; set; }
    float Duration { get; set; }
}

What would be the best way to add a list of tracks to the IAlbum interface? What if I w开发者_如何学Pythonanted the individual tracks to be properties and not have an exposed array of tracks?


Use an indexer. Specifically:

    ITrack this[int trackIndex]
    {
        get;
    }


The list of tracks could be either:

IList<ITrack> Tracks {get;}

or

IEnumerable<ITrack> Tracks {get;}

If you want the concrete type to expose a more concrete API, you could implement the above via explicit implementation.

You could in theory make:

interface IAlbum : IEnumerable<ITrack> {...}

but I don't think that is a good idea.

Re exposing tracks as properties; if I understand correctly, you could do this "kind of" at runtime by implementing ICustomTypeDescriptor on the concrete album type. But it is non-trivial and a bit messy - and it won't help hugely unless you are using data-binding.


You could also provide an indexer that works with a track title. This is [sort of] between properties for the tracks and having a collection.

ITrack this[string trackName]
{
    get { return getTraxckUsingName(trackName); }
}
0

精彩评论

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