繁体   English   中英

如何在c#中访问另一个类中的类的私有函数?

[英]How to access private function of a class in another class in c#?

我是c#编程的新手,我知道类的公共数据成员可以从另一个类访问。有什么方法可以从另一个类访问私有函数?

这就是我试过的。请帮助我。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication7
{
    class Program
    {
        private class Myclass
        {
            private int Add(int num1, int num2)
            {
                return num1 + num2;
            }
        }
        static void Main(string[] args)
        {
            Myclass aObj = new Myclass();
            //is there any way i can access private function
        }
    }
}

您好,您可以使用反射来获取类的任何组件。

这是一个演示。 试试吧

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ExposePrivateVariablesUsingReflection
{
    class Program
    {
        private class MyPrivateClass
        {
            private string MyPrivateFunc(string message)
            {
                return message + "Yes";
            }
        }

        static void Main(string[] args)
        {
            var mpc = new MyPrivateClass();
            Type type = mpc.GetType();

            var output = (string)type.InvokeMember("MyPrivateFunc",
                                    BindingFlags.Instance | BindingFlags.InvokeMethod |
                                    BindingFlags.NonPublic, null, mpc,
                                    new object[] {"Is Exposed private Member ? "});

            Console.WriteLine("Output : " + output);
            Console.ReadLine();
        }
    }
}

除了使用反射,你不能。 事实上,成员完全是private因此无法从课堂外访问。

从我在您的代码中看到的,我认为您想要的是具有可访问的Add功能。

如果它是你想要的,你不需要这个类,只需将你的Add函数放在你的Program类中并使它成为static

如果你真的需要你的课程,那么你应该问自己一个问题:我编写的函数是为了在课堂外可以访问,还是应该只在我的课程中调用。

如果第一个问题的答案是肯定的,那么将其公之于众。

这是一个设计问题,所以你应该专注于此。

即使你可以使用反射来访问它,但是很少有这样做的好事。 反思是最后的手段,如果你能以另一种方式做到,你应该用另一种方式。

你可以通过反思,但为什么你想这样做?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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