.net - How to specialize an inherited List to a List in C#? -



.net - How to specialize an inherited List<SuperClass> to a List<SubClass> in C#? -

this sounds mutual problem, whats best practice if have base of operations class public property of type list<superclass> , inherit list in class b want utilize more specialized type parameter list:

class superclass { public bool flag; } class subclass : superclass { public int number; } class { public list<superclass> elements { get; } } class b : { public list<subclass> elements { get; set; } }

so how can in overwrite elements list new list, still create sure accessed if class knows objects?

class c { list<a> alist; void filllist() { alist.add(new b()); } void dosomething() { foreach (var in alist) forach(var super in a.elements) super.flag = true; } }

you cannot. because stands, if insert superclass through interface, b fail, because superclass cannot inserted b's subclass list.

the specific terms should google covariance , contravariance.

your scenario can solved if restrict classes read access @ to the lowest degree in base of operations class. have 2 read-only properties in b class, 1 specialized, 1 not specialized returning specialized version.

c# .net inheritance collections

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -