简体   繁体   中英

How to call Method of Private Property using Reflection in c#?

I have some problems with my project.

I want to call one method from private Property like private clsBUS_DEMO prop_DEMO

clsBUS_DEMO has a Method, which Name is public void SayHello() .

This is my code

PropertyInfo p = this.GetType().GetProperty("SayHello");

p is null because program can't find prop_DEMO

Can anybody help me about this?

Call a method of private property? Not sure if I understood what you want, it would be useful to have the class that represent you object. Do you mean call a property that returns an object and then call a method of that object?

Anyways, I think there's a lot information out there about that topic, for example: How do I use reflection to invoke a private method? Find a private field with Reflection?

class MyClass1
{
    public MyClass1()
    {
        Prop = new MyClass2();
    }

    public MyClass2 Prop { get; set; } 
}

class MyClass2
{
    private int Test()
    {
        return 5;
    }
}

static void Main(string[] args)
{
    var obj = new MyClass1();
    var obj2 = obj.Prop;

    var propInfo = obj.GetType().GetProperty("Prop");

    var obj2Reflection = propInfo.GetValue(obj, null);
    var dynMethod = obj2.GetType().GetMethod("Test", BindingFlags.NonPublic | BindingFlags.Instance);
    var obj2Return = dynMethod.Invoke(obj2, null);
}

clsBUS_DEMO prop_DEMO is not a property, it's a Field . You need to use GetFields to get it and also since it's private you need to pass BindingFlags.NonPublic and BindingFlags.Instance .

Here is a sample of how you should do it

 static void Main(string[] args)
    {
        Bar bar = new Bar();
        Foo foo = (Foo)bar.GetType().GetField("a", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(bar);
        foo.GetType().GetMethod("ShowMessage").Invoke(foo,new object[] { });
    }
    public class Bar
    {
        private Foo a;
        public Bar()
        {
            a = new Foo();
        }
    }
    public class Foo
    {
        public void ShowMessage()
        {
            Console.WriteLine("Hello World!");
        }
    }

Okay guys!

I'm done :)

I just Create Property get{} set{} and use this code :D

PropertyInfo p = this.GetType().GetProperty("LoaiSP_BUS", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

Thanks all!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM