Calling functions dynamically

  • Thread starter Thread starter hardieca
  • Start date Start date
H

hardieca

My apologies if this gets posted twice...

I am trying to determine whether or not a class has a function, and if
it does, build a reference to it dynamically which I can then use to
access the original function's functionality.

So, for the first part, I'm looking for some way to do the following:

if (hasMember(object o, string member){
//Processing

Then, if the object does have the function, I want to build a reference
to the function I can then use:

functionRef = buildFunctionRef(object System.Convert, string
"ToInt16");

x = functionRef("100"); // x is an int equal to 100.

It's important that the member be passed as a string as the string
parameter will be dynamically concatenated as the application runs.

I'm fairly new to C#, but I'm looking for something similar to Python's
getattr function. Let me know if I haven't been clear.

Regards,

Chris
 
You are looking for System.Reflection.MethodInfo. Here is a brief
example that uses it. Note that if the method is overloaded or is
nonpublic this code will need to be altered accordingly. If you need
an example with the above criteria let me know.

using System;

class TestClassWithDesiredMember
{
public int TestFunction(string var)
{
return Convert.ToInt32(var);
}
}

class MainClass
{
static void Main(string[] args)
{
TestClassWithDesiredMember testObject =
new TestClassWithDesiredMember();

System.Reflection.MethodInfo mInfo =
testObject.GetType().GetMethod("TestFunction");

if(mInfo == null)
{
Console.WriteLine("No such method!");
}
else
{
int result = (int)mInfo.Invoke(testObject, new object[1] {"100"});
Console.WriteLine("Integer Value: " + result.ToString());
}
}
}
 
Chris,

This is actually pretty easy using reflection. I think the following
example will get you on the right track.

public void Example()
{
string methodName = "GetHashCode";

Object o = new Object();

MethodInfo method = o.GetType().GetMethod(methodName);
if (method != null)
{
object result = method.Invoke(o, null);
Console.WriteLine(methodName + " = " + result.ToString();
}
}

Brian
 

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

Back
Top