Dynamic call object in C#

M

Michael

Hi all :

in vb.net I know use the follow code can implement dynamic call
Dim asm As [Assembly] = [Assembly].LoadFrom(<FileName>)
Dim ty As Type = asm.GetType(<Object Name and class name>)
Dim obj As Object = Activator.CreateInstance(ty)
obj.popupmsg()

how can I implement in C#

Thx
 
P

Peter Rilling

Pretty much the same way, but you might need to cast the "obj" variable to
the type that has the desired method.
 
A

Adam Clauss

Dim asm As [Assembly] = [Assembly].LoadFrom( said:
Dim ty As Type = asm.GetType(<Object Name and class name>)
Dim obj As Object = Activator.CreateInstance(ty)
obj.popupmsg()

Assembly asm = Assembly.LoadFrom(<FileName>);
Type ty = asm.GetType(<Object Name and class name>);
object obj = Activator.CreateInstance(ty);

Here you run into a problem (and I didn't realize your above code would work
in VB.Net).
The obj variable is of type 'object' - and the object class obviously does
not define the popupmsg() method.

You have two options.
1) If the code you are writing contains the definition for the 'real' type
of obj, you can cast it, and then call popupmsg:
SomeType someType = obj as SomeType;
if (someType != null)
{
someType.popupmsg();
}


2) If you do not have this definition, you will have to use reflection to
access the method and call it. Note - you may need to change the flags
passed to GetMethod:

MethodInfo popupMethod = ty.GetMethod("popupmsg", BindingFlags.Instance |
BindingFlags.Public);
if (popupMethod != null)
{
popupMethod.Invoke(obj, null);
}


HTH

--
Adam Clauss

Michael said:
Hi all :

in vb.net I know use the follow code can implement dynamic call
Dim asm As [Assembly] = [Assembly].LoadFrom(<FileName>)
Dim ty As Type = asm.GetType(<Object Name and class name>)
Dim obj As Object = Activator.CreateInstance(ty)
obj.popupmsg()

how can I implement in C#

Thx
 
A

Adam Clauss

Adam Clauss said:
Assembly asm = Assembly.LoadFrom(<FileName>);
Type ty = asm.GetType(<Object Name and class name>);
object obj = Activator.CreateInstance(ty);
2) If you do not have this definition, you will have to use reflection to
access the method and call it. Note - you may need to change the flags
passed to GetMethod:

MethodInfo popupMethod = ty.GetMethod("popupmsg", BindingFlags.Instance |
BindingFlags.Public);
if (popupMethod != null)
{
popupMethod.Invoke(obj, null);
}

In reading your post again - since you have to use Activator.CreateInstance
(rather than just normally constructing the object), you will almost
certainly need to use the second option (Reflection).
 

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