Reputation: 12064
Considering the following setup, how can I restrain IConnection
to only contain IPort
of the same ConnectionType
in Ports
? Maybe I am overlooking something obvious here:
Enum ConnectionType
{
Undefined,
Type1,
Type2
}
IConnection
{
ConnectionType ConnectionType {get;set}
IEnumerable<IPort> Ports {get;set;}
}
IPort
{
ConnectionType ConnectionType {get;set;}
}
Upvotes: 3
Views: 262
Reputation: 2622
How about wrapping up the enum and using generics?
public interface IConnectionType
{
ConnectionTypeEnum Connection{ get; set;}
}
public enum ConnectionTypeEnum
{
Undefined,
Type1,
Type2
}
public interface IPort<T> where T : IConnectionType
{
}
public interface IConnection<T> where T : IConnectionType
{
IEnumerable<IPort<T>> Ports {get;set;}
}
I'm not sure if there's any point in having the enum anymore though
Upvotes: 2
Reputation: 61617
Instead of having the connection type in the IPort interface, have a property of IConnection, e.g.
IConnection
{
ConnectionType ConnectionType { get; }
IEnumerable<IPort> Ports { get; }
}
IPort
{
IConnection Connection { get; }
}
Management of these properties should be left to the implementation.
Upvotes: 0
Reputation: 499392
In order to control the type of IPorts
, you will need to change the class to not expose the list in a writeable manner.
Make the property read-only, returning a new ReadOnlyCollection
to prevent adding any type of IPort
to the internal collection. Add an AddPort
method that will only allow adding an IPort
of the right type.
Upvotes: 2
Reputation: 117360
You cannot enforce such constraints at compile time.
You will have to do some checking at runtime.
Upvotes: 3