Skip to main content
Microsoft Silverlight
Home Forums Silverlight Programming Programming with .NET - General Reflection on SilverLight. How can we call the private method
4 replies. Latest Post by decius on August 13, 2009.
(0)
haughtycool
Member
81 points
35 Posts
09-30-2008 4:37 AM |
I think the reflection library on SL has a bug. When I call a private method, the system always throws exception MethodAccessException.
ConstructorInfo ci = typeof(Hello).GetConstructor(BindingFlags.NonPublic| BindingFlags.Instance ,null,System.Type.EmptyTypes,null); object helloObject = ci.Invoke(System.Type.EmptyTypes); MethodInfo[] helloObjectMethods = helloObject.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly| BindingFlags.Instance ); foreach (MethodInfo mi in helloObjectMethods) { mi.Invoke(helloObject, System.Type.EmptyTypes); } Console.ReadLine();
1 public class Hello2 {3 public Hello()4 {5 System.Diagnostics.Debug.WriteLine("Private Constructor");6 }7 public void HelloPub()8 {9 System.Diagnostics.Debug.WriteLine("Public Hello");10 }11 private void HelloPriv()12 {13 System.Diagnostics.Debug.WriteLine("Private Hello");14 }15 }
However when I use this code in a Windows Form Application, it runs well.
PS: I get this source code from the blog of this guy: http://www.canerten.com/reflection-with-private-members
I don't break out the copyright law
amit_pal...
Participant
1150 points
201 Posts
09-30-2008 6:50 AM |
Moving from Alpha to Beta and then to release mode, Microsoft has been more concerned about the security.
This means that now everything is SecuritySafeCritical and we cannot call any private methods using reflection. VS might be able to discover them however you will not be able to call them.
I am not linked to Microsoft however i think this is good (if this will be implemented in RTW)
Please mark this post as 'Answered' if this answers your question
09-30-2008 9:56 PM |
I think when we use reflection, we should able to do everything, we should able to access to private, protected method and property.
In Java, we have the function Method.SetAccessible(bool flag), so we easy to call the private method
In .Net 3.5, We have the BindingFlag, so we can find the private and protected method, and we can invoke them
However in SilverLight, we can't.
The main idea I want to talk about is why .Net 3.5 can invoke private method but SL can't.
10-03-2008 5:48 AM |
Everything rests on Security. However, it seems that Microsoft is not willing to provide private access in case of Reflection.
decius
26 points
66 Posts
08-13-2009 3:12 PM |
It makes sense to me. Exposing private methods to reflection on the client could be a serious security risk. If what you're trying to do absolutely relies on reflecting a private method and there's no way around it, perhaps you might want to reconsider the encapsulation on your classes.