vb.net - Is there a way to dynamically specify property names in a class? -


vb.net 2010~framework 3.5

is there way dynamically specify property names of class?

sometimes need list created prop1 , prop2 other times need list created prop2 , prop4 etc.. target properties not known ahead of time, change app running. . .

option strict on option explicit on public class form1  private class things     public property prop1 string     public property prop2 string     public property prop3 string     public property prop4 string end class  private class subthing     public property p1 string     public property p2 string end class  private sub button1_click(sender system.object, e system.eventargs) handles button1.click     dim mainlst new list(of things)      dim count integer      until count = 20         mainlst.add(new things {.prop1 = count.tostring, _                                      .prop2 = (count + 1).tostring, _                                      .prop3 = (count + 2).tostring, _                                      .prop4 = (count + 3).tostring})         count += 1     loop      ' need dynamically pick properties mainlst sublst.     ' commented code below wont compile demonstrates i'm trying     ' can done without looping?      'dim propnamea string = "prop1"  ' dynamically specify property name     'dim propnameb string = "prop4"     'dim sublst = mainitem in mainlst     '             select new subthing() {.p1 = mainitem.propnamea, .p2 = mainitem.propnameb}       ' code below compiles lacks dynamics need?     dim sublst = mainitem in mainlst                   select new subthing() {.p1 = mainitem.prop1, .p2 = mainitem.prop4} end sub 

the direct approach use callbyname (msdn link). i'm assuming example simplified version of you're working with, seems better approach rid of prop1, prop2, ... string properties , use list(of string) can index into, without having frankenstein property names index value. example:

public property props list(of string)  '...  dim sublst = mainitem in mainlst                   select new subthing() {.p1 = mainitem.props(1), .p2 = mainitem.props(4)} 

not sure exact use case example, points in right direction.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -