I'd like to have a List of Class Types (not a list of Class instances) where each member of the List is a Subclass of MyClass.
For example, i can do this:
List<System.Type> myList;
myList.Add(typeof(mySubClass));
but i'd like to restrict the list to only accept subclasses of MyClass.
This is distinct from questions like this . Ideally i'd like to avoid linq, as it's currently unused in my project.
Servy is right in his comment , and Lee in his : it's much more preferable to compose than inherit . So this is a good option:
public class ListOfTypes<T>
{
private List<Type> _types = new List<Type>();
public void Add<U>() where U : T
{
_types.Add(typeof(U));
}
}
Usage:
var x = new ListOfTypes<SuperClass>();
x.Add<MySubClass>()
Note that you can make this class implement an interface like IReadOnlyList<Type>
if you want to give other code read access to the contained Type
s without other code having to depend on this class.
But if you want to inherit anyway, you could create your own class that inherits from List
, then add your own generic Add
method like this:
public class ListOfTypes<T> : List<Type>
{
public void Add<U>() where U : T
{
Add(typeof(U));
}
}
Just be aware of what Lee said : with this second version you can still Add(typeof(Foo))
.
You should derive a list class from List and override the Add method to perform the type checking that you need. I'm not aware of a way in .NET to do that automatically.
Something like this could work:
public class SubTypeList : List<System.Type>
{
public System.Type BaseType { get; set; }
public SubTypeList()
: this(typeof(System.Object))
{
}
public SubTypeList(System.Type baseType)
{
BaseType = BaseType;
}
public new void Add(System.Type item)
{
if (item.IsSubclassOf(BaseType) == true)
{
base.Add(item);
}
else
{
// handle error condition where it's not a subtype... perhaps throw an exception if
}
}
}
You would need to update the other methods that add/update items to the list (index setter, AddRange, Insert, etc)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.