【发布时间】:2018-10-09 23:21:40
【问题描述】:
我有一个名为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,我应该如何访问它?
【问题讨论】:
-
如果你需要在外面访问它,为什么它首先是私有的?
-
反射或更改访问修饰符。
-
@Broots Waymb 好吧,我没有把它设为私有。 Scenario2 是 Microsoft 在 git 上直接提供的示例。
-
微软将该方法设为私有可能是有充分理由的。
-
问陈规定型的留言板问题:您为什么要这样做?你想达到什么目的? 也就是说,可以使用反射调用私有方法。
标签: c#