locked
Access Private method of a class using delegate RRS feed

  • Question

  • Hi,


    I want to access private method from another class using delegate.

    Thanks
    John
    Wednesday, September 2, 2009 6:00 AM

Answers

  • Or are you looking for something like this:

    	public class Child {
    		private int something;
    		
    		public event EventHandler Changed;
    		
    		private void OnChanged() {
    			if (Changed != null) {
    				Changed(this, EventArgs.Empty);
    			}
    		}
    
    		public int Something {
    			get { return something; }
    			set {
    				something = value;
    				OnChanged();
    			}
    		}
    	}
    
    	public class WatchChild {
    		private Child child;
    
    		public WatchChild(Child watch) {
    			child = watch;
    			child.Changed += new EventHandler(test_Changed);
    		}
    
    		private void test_Changed(object sender, EventArgs e) {
    			// Property of child changed
    			// Do something
    		}
    	}
    
    Where the test_Changed is a private function called from the Child class using an event.

    If our answers are still not what you looking for, than give us an example of what you want to accomplish
    • Proposed as answer by boothwine Saturday, September 12, 2009 10:37 AM
    • Marked as answer by eryang Thursday, October 8, 2009 8:43 AM
    Monday, September 7, 2009 10:52 AM

All replies


  • beat the encapsulation ? If it can be done, I want to know !



    Thanks

    My BlogMy FlickrMy Facebook
    Wednesday, September 2, 2009 7:36 AM
  • I think you can do that with reflection.

    Get the method from the type and invoke it.

    Example from the msdn library:

    using System;
    using System.Reflection;
    using System.Windows.Forms;

    public class A
    {
    public virtual int method () {return 0;}
    }

    public class B
    {
    public virtual int method () {return 1;}
    }

    class Mymethodinfo
    {
    public static int Main()
    {
    Console.WriteLine ("\nReflection.MethodInfo");
    A MyA = new A();
    B MyB = new B();

    // Get the Type and MethodInfo.
    Type MyTypea = Type.GetType("A");
    MethodInfo Mymethodinfoa = MyTypea.GetMethod("method");

    Type MyTypeb = Type.GetType("B");
    MethodInfo Mymethodinfob = MyTypeb.GetMethod("method");

    // Get and display the Invoke method.
    Console.Write("\nFirst method - " + MyTypea.FullName +
    " returns " + Mymethodinfoa.Invoke(MyA, null));
    Console.Write("\nSecond method - " + MyTypeb.FullName +
    " returns " + Mymethodinfob.Invoke(MyB, null));
    return 0;
    }
    }
    Wednesday, September 2, 2009 8:01 AM
  • Yes,
    we can be achieve by reflection but i want to know how we will do that with the help of delegate

    Thanks

    John
    Wednesday, September 2, 2009 8:13 AM
  • Can you be more specific about what you are trying to achieve.
    You can only (as far as I know) create a delegate for a method if you access to it.
    So the class holding the private function should return somehow the delegate to this method.
    Wednesday, September 2, 2009 9:30 AM
  • Let the class with the private method expose a public property that returns a delegate instance.  Pretty pointless exercise though.

    Hans Passant.
    • Proposed as answer by boothwine Saturday, September 12, 2009 10:37 AM
    Thursday, September 3, 2009 12:31 AM
  • There is no private method in both class.

    there should be any one of the private method in the any of the class and then access.

    my concern is hat i have to access private method of class using delegate and event.

     

    Thanks
    John
    Saturday, September 5, 2009 12:22 PM
  • You should get a MethodInfo of your method using Reflection first. How to do this is shown above excepting you need to give BindingFlags.NonPublic (and BindingFlags.Instance if you need an instance method) to GetMethod() call.
    Then you can construct a delegate calling static method Delegate.CreateDelegate() and passing a delegate type and MethodInfo from the previous step.
    Saturday, September 5, 2009 12:31 PM
  •  

        class Class1

        {

            public Action<object> InvokeTargetMethod;

     

            public class31()

            {

                this.InvokeTargetMethod = TargetMethod;

            }

     

            private void TargetMethod(object obj)

            {

            }

        }


    Mark the best replies as answers. "Fooling computers since 1971."
    • Proposed as answer by boothwine Saturday, September 12, 2009 10:36 AM
    Saturday, September 5, 2009 12:35 PM
  • You can do it this way without a delegate.

     

     

        public class Class1

        {

            private void PrivateMethod()

            {

                Console.WriteLine("Private Method has been called.");

            }

            public void Method1()

            {

                Console.WriteLine("Public Method has been called.");

            }

        }

     

    /************************************************************/

     

        class MethodInvoker

        {       

            public MethodInfo privateMethod;

            string typeName;

            string methodName;

            public MethodInvoker()

            {

                return;

            }

            public MethodInvoker(bool create, string typeName, string methodName)

            {

                this.typeName = typeName;

                this.methodName = methodName;

                if (create)

                {

                    this.Initialize();

                }

            }

     

            void Initialize()

            {

                Assembly asm = Assembly.GetExecutingAssembly();  // get the target assembly

                Type[] types = asm.GetTypes();  // get all of the defined types

                MethodInfo[] mi = new MethodInfo[1];  // instantiate object for compiler.

                foreach (Type t in types)

                {

                    if (t.Name == typeName)

                    {

                        mi = t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

                    }

                }

                foreach (MethodInfo m in mi)

                {

                    if (m.Name == methodName)

                    {

                        this.privateMethod = m;

                    }

                }

                

            }

        }

     

    /************************************************************/

     

     

     

            static void CallPrivateMethodTest()

            {

                Class1 c = new Class1();

                MethodInvoker invoker = new MethodInvoker(true, "Class1", "PrivateMethod");

                invoker.privateMethod.Invoke(c, null);

            }


    Mark the best replies as answers. "Fooling computers since 1971."
    Sunday, September 6, 2009 7:41 PM
  • Or are you looking for something like this:

    	public class Child {
    		private int something;
    		
    		public event EventHandler Changed;
    		
    		private void OnChanged() {
    			if (Changed != null) {
    				Changed(this, EventArgs.Empty);
    			}
    		}
    
    		public int Something {
    			get { return something; }
    			set {
    				something = value;
    				OnChanged();
    			}
    		}
    	}
    
    	public class WatchChild {
    		private Child child;
    
    		public WatchChild(Child watch) {
    			child = watch;
    			child.Changed += new EventHandler(test_Changed);
    		}
    
    		private void test_Changed(object sender, EventArgs e) {
    			// Property of child changed
    			// Do something
    		}
    	}
    
    Where the test_Changed is a private function called from the Child class using an event.

    If our answers are still not what you looking for, than give us an example of what you want to accomplish
    • Proposed as answer by boothwine Saturday, September 12, 2009 10:37 AM
    • Marked as answer by eryang Thursday, October 8, 2009 8:43 AM
    Monday, September 7, 2009 10:52 AM
  • Though a bit late :) I hope this was what u were looking for

     

    class LearnDelegate
        {
        
            private void method1(int num)
            {
                Console.WriteLine("private method called");
            }
        }

     

     class Program
        {
         
            public static void Main(string[] args)
            {
                var learnDelegate = new LearnDelegate();
                var callPrivate = (Action<int>)
                    Delegate.CreateDelegate(typeof(Action<int>), learnDelegate, "method1");
                callPrivate(5);
                Console.Read();
            }
         
        }

     

    Wednesday, June 29, 2011 4:26 AM