Jon Skeet wrote:
Well, just looking at your code again, you're using
BindingFlags.GetProperty, which probably isn't what you're after for a
method call.
So sorry for the mistake I made during copying code to this post!! The original
code snippet should be:
//...
MyControl instance = new MyControl();
Type type = instance.GetType();
object[] args = new object[] {"images/test.gif"};
string path = (string)type.InvokeMember("ResolveClientUrl",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.InvokeMethod,
null, instance, args); // Exception is thrown, withou no such member
found in the derived class.
//...
The reason why I made this mistake is actually I've wrote a helper class
as the following:
// code starts
using System;
using System.Reflection;
namespace LaserWeb.Presentation.Common
{
internal sealed class Reflector
{
private Reflector() {}
public static object GetProperty(object instance, string name)
{
Type type = instance.GetType();
return type.InvokeMember(name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.GetProperty,
null, instance, null);
}
public static object GetProperty(Type type, object instance, string name)
{
return type.InvokeMember(name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.GetProperty,
null, instance, null);
}
public static object InvokeMethod(object instance, string name, object[]
args)
{
Type type = instance.GetType();
return type.InvokeMember(name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.InvokeMethod,
null, instance, args);
}
public static object InvokeMethod(Type type, object instance, string name,
object[] args)
{
return type.InvokeMember(name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.InvokeMethod,
null, instance, args);
}
}
}
// code ends
When I posted the puzzle, the original code snippet is not handy (I have
removed it from my project), so I made the wrong code snippet by copying
the code fragment from Reflector.GetProperty() and modifing base on that
code. That's the reason why I made the mistake, sorry again for misleading
all of you in your reading!
If you use the above helper class as the following, you will still find the
problem I described:
// ..
MyControl instance = new MyControl();
object args = new objet[] {"images/test.gif"};
Reflector.InvokeMethod(typeof(System.Web.UI.Contro l), instance, "ResolveClientUrl",
args); // This will works fine.
Reflector.InvokeMethod(instance, "ResolveClientUrl", args); // An exception
will be thrown here, indicating member not found.
// ...
I don't know why I had encountered such a strange problem, and got puzzled.
You may make the similar sample code and have a try, to see whether what
I said would happen. Thanks:)
Laser Lu.