Property of List of Classes

Z

zacks

I asked this question before but got no responses. Let me rephrase the
question. I have a class that as a property defined as a list of
classes.

Public Class ClassA

Public Property Prop1 as List(of ClassB)

In a code segment, I can add an instance of ClassB to the Prop1
property of an instance of ClassA with the statement:

myClassA.Prop1.Add myClassB

Can I add an instance of ClassB to the Prop1 List using the
..InvokeMember method of the Type class?
 
C

Carlos J. Quintero [VB MVP]

Try:

Public Class ClassB

End Class

Public Class ClassA
Public Prop1 As New List(Of ClassB)
End Class

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim objA As New ClassA
Dim objArray(0) As ClassB

objA.Prop1.Add(New ClassB)

objArray(0) = New ClassB
objA.Prop1.GetType.InvokeMember("Add", Reflection.BindingFlags.Instance
Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.InvokeMethod,
Nothing, objA.Prop1, objArray)

MessageBox.Show(objA.Prop1.Count.ToString) ' Result: 2

End Sub

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio
You can code, design and document much faster:
http://www.mztools.com
 
Z

zacks

Carlos said:
objArray(0) objA.Prop1.GetType.InvokeMember("Add", Reflection.BindingFlags.Instance
Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.InvokeMethod,
Nothing, objA.Prop1, objArray)

Oh, man, I was thinking the only way to set a property value in
InvokeMethod was to use the bindings flag of SetProperty. I never
thought of Invoking the Add method!! Very elegant. I will try your
suggestion!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top