vb.net - So a VB interface can't have shared functions. Is there an alternative to creating dummy objects? -
to avoid getting weeds on particular program, let me create simplified case.
i have generic class should work on variety of objects. each of objects must implement interface.
what want like:
public interface genthing shared function thing_name() string ' doesn't work! can't shared! sub fillone(row datarow) end interface public class thing1 implements genthing public shared function thing_name() string implements genthing.thing_name return "thing number one" end function public sub fillone(row datarow) implements genthing.makeone ... bunch of work ... end sub end class public class thingutil(of t {genthing,new}) public function getlist(id integer) list(of t) dim name=t.thing_name() ' doesn't work! dim ds dataset=getdata(name,id) ' bunch of work here that's whole point of class not relevant question dim my_list = new list(of t) each row datarow in ds.tables(0).rows dim my_t = new t() my_t.fillone(row) my_list.add(my_t) next return my_list end function end class
do problem? need every class implements interface have function returns "name" used data needed create instance of object. need know name before create instance, because need able create instance. vb doesn't allow interface have shared function, want write doesn't work.
so i've done this:
i make thing_name not shared.
then instead of "dim name=t.thing_name()", write
dim dummy = new t() dim name = dummy.thing_name()
okay, works, seems ugly. create instance of object, overhead that involves, piece of constant text.
is there better way? or making big deal out of nothing?
update
i see 2 people voted close question on grounds same "why can't have shared functions in interface?"
i not asking why can't have shared. saying, given can't, how solve particular problem?
there's no simple way of fixing this, no.
depending on thing_name
does, however, might approach things in different way. if each implementation returns constant value, it's metadata class - , described in attribute instead, can fetched @ execution time. (see type.getcustomattributes
.) unfortunately can't enforce types implementing interface decorated attribute - could write unit test check pretty easily.
if thing_name
needs work @ execution time, that's tougher. potentially well-known shared method name instead , execute via reflection (and again have unit tests check it's implemented properly).
Comments
Post a Comment