Is there a way to say an IList<xxx> is both a specific class and an interface

StackOverflow https://stackoverflow.com/questions/11525678

  •  21-06-2021
  •  | 
  •  

Domanda

I would like to declare a property as:

IList<BaseNode and IComplexType> ComplexTypes { get; }

All elements in the list inherit from BaseNode and implement IComplexType. Is there any way to do this? It won't work to create a class BaseNodeComplexType because the nodes in the list are all sub-classes of BaseNode.

Update: I didn't think this through to explain fully. I have sub classes such as XmlNode. XmlNode inherits from BaseNode. I also have XmlComplexNode that inherits from XmlNode and implements IComplexType. But XmlNode does not inherit from IComplexType (and I don't want it to as I use "obj is IComplexType" in places. apologies for not adding this originally.

È stato utile?

Soluzione

No, but you could solve it with generics?

class CustomObj<T> where T : BaseNode, IComplexType
{
   IList<T> ComplexTypes { get; }
}

For more details about the used generic-constraints, see this page.

Altri suggerimenti

The correct behaviour would be to derive a new class i.e. ComplexBaseNode which has both the inherited features of BaseNode and interface IComplexType, would it not?

There's no direct way to do that.

But you can use generics to achieve that: what about a generic type parameter?

public class YourClass<T> 
  where T : BaseNode, IComplexType

... and your property will look like this:

IList<T> ComplexTypes { get; }

Where's your IList<> residing. If you use a generic parameter xxx (from your title), you can say where xxx : BaseNode, IComplexType.

Also consider if BaseNode could already implement IComplexType, possibly abstractly.

The definition of IList<T> means that you can only specify one type for the elements in the list.

Create a container class: ComplexNodeContainer<T,U>, that will contain BaseNode objects implementing also IComplexType, when T=BaseNode and U=IComplexType.

When you set the "contained" object(in the constructor preferably, or via a method/property), you can check whether it implements both types or not, and act accordingly.

You can have two properties to retrieve it, one as type T (or BaseNode), one as type U (or IComplexType in this case).

Then you can define your property as: IList<ComplexNodeContainer>

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top