vb.net - How should I store Child Classes in an enumerable and how to access them correctly? -
public class uniquelist(of t baseclass) inherits list(of t) public overridable overloads sub add(value t) if not me.contains(value) mybase.add(value) end sub public function [get](val integer) t homecoming me.where(function(cb) cb.id = val)(0) end function end class
i en error if seek utilize without casting first, i cast before trying object :
dim mylist new uniquelist(of baseclass) mylist.add(new childclass(1)) dim x childclass= (mylist.get(1)) x.randommethod() ... so tried create new function in uniquelist class cast me :
public function [getchildclass](val integer) childclass homecoming directcast(me.where(function(cb) cb.id = val)(0), childclass) end function but errors saying value t cannot converted childclass... there way have function returns me right object ?
edit: cant alter list of childclass ...
edit : declare them want ...
class baseclass public id integer public sub new(id integer) me.id = id end sub end class class childclass inherits baseclass public sub new(id integer) mybase.new(id) end sub public sub randommethod() 'do nil end sub end class
you may looking this:
public function [getparent](val integer) childclass homecoming directcast(me.oftype(of childclass). where(function(cb) cb.id = val)(0), childclass) end function note - fail if no elements of type childclass found, can prevent failing using .firstordefault instead of manually indexing (0) first element. firstordefault homecoming nothing if no elements found.
vb.net
No comments:
Post a Comment