从C#中的另一个类调用私有函数

时间:2018-10-09 14:31:51

标签: c#

我有一个名为Scenario2_Client.xaml.cs的程序,它具有以下功能:

namespace SDKTemplate
{

    public sealed partial class Scenario2_Client : Page
    {
        private MainPage rootPage = MainPage.Current;
        // code

        // this is the function I would like to call
        private void RemoveValueChangedHandler() 
        {
            ValueChangedSubscribeToggle.Content = "Subscribe to value changes";
            if (subscribedForNotifications)
            {
                registeredCharacteristic.ValueChanged -= Characteristic_ValueChanged;
                registeredCharacteristic = null;
                subscribedForNotifications = false;
            }
        }
        // ...
    }
}

然后我在另一个文件(但在同一项目中)中添加了一个名为EchoClient.cs的类,该类具有以下代码:

namespace SDKTemplate
{
     class EchoClient
     {
         public void TcpClient()
         {
             try
             {
                 TcpClient client = new TcpClient("139.169.63.130", 9999);
                 StreamReader reader = new StreamReader(client.GetStream());
                 StreamWriter writer = new StreamWriter(client.GetStream());
                 string s = string.Empty;
                 while (!s.Equals("Exit"))
                 {
                     Console.WriteLine("TCP Client connected....");
                     Console.WriteLine("Enter a string or number to send to the server: ");
                     s = Console.ReadLine();                    
                     writer.WriteLine(s);
                     writer.Flush();
                     string server_string = reader.ReadLine();
                     Console.WriteLine(server_string);
                 }

                 reader.Dispose();
                 writer.Dispose();
                 client.Dispose();

             }
             catch (Exception e)
             {
                 Console.WriteLine(e);
             }
         }
     }


    internal class Console
    {
        internal static string ReadLine()
        {
            throw new NotImplementedException();
        }

        internal static void WriteLine(string v)
        {
            throw new NotImplementedException();
        }

        internal static void WriteLine(Exception e)
        {
            throw new NotImplementedException();
        }


    internal class TcpClient
    {
        private string v1;
        private int v2;

        public TcpClient(string v1, int v2)
        {
            this.v1 = v1;
            this.v2 = v2;
        }

        internal void Dispose()
        {
            throw new NotImplementedException();
        }

        internal Stream GetStream()
        {
            throw new NotImplementedException();
        }
    }    
 }

是否可以从此类中调用该函数?

如果它是公开的,我会做这样的事情:

EchoClient client = new EchoClient()
client.somefunction();
client.somefunction();

..但是由于此方法是private,我应该如何访问它?

2 个答案:

答案 0 :(得分:1)

可以如下所述使用反射来调用私有方法。

var iMethod
  = client.GetType().GetMethod("somefunction",
                               BindingFlags.NonPublic | BindingFlags.Instance);
iMethod.Invoke(client, new object[]{});

答案 1 :(得分:0)

我不确定为什么@Codor会被否决,但这是相同的答案。首先,我使用私有方法创建一个类:

public class PrivateFunction
{
    private int _age;

    public PrivateFunction(int age)
    {
        _age = age;
    }

    private int DoSomethingPrivate(string parameter)
    {
        Debug.WriteLine($"Parameter: {parameter}, Age: {_age}");
        return _age;
    }
}

我创建了一个方法,该方法接受参数并返回一个整数以显示所有可能性。

然后我称之为:

   var type = typeof(PrivateFunction);
   var func = type.GetMethod("DoSomethingPrivate", BindingFlags.Instance | BindingFlags.NonPublic);
   var obj = new PrivateFunction(12);
   var ret = func.Invoke(obj, new[] {"some parameter"});
   Debug.WriteLine($"Function returned {ret}");

我在输出中得到这个(证明发生了什么事):

Parameter: some parameter, Age: 12
Function returned 12

如果要重复调用同一函数(可能带有不同的对象),请将MethodInfo对象保存在func中。它是不变的且可重复使用的。