C#反射调用类的私有方法
2021-05-23 03:31
标签:pre lin info write invoke 实例化 tst var NPU C#反射调用类的私有方法 标签:pre lin info write invoke 实例化 tst var NPU 原文地址:https://www.cnblogs.com/xiefengdaxia123/p/11144054.htmlvoid Main()
{
var type = typeof(StockClass);
type.Dump();
var fields=type.GetFields(BindingFlags.Instance|BindingFlags.NonPublic).Dump("字段");
var members = type.GetMethods().Dump("方法");
//调用私有的构造函数,获得实例化对象
object obj=type.GetConstructors(BindingFlags.Instance|BindingFlags.NonPublic)[0].Invoke(null);
//获得私有方法
var method = type.GetMethod("GetStr", BindingFlags.Instance | BindingFlags.NonPublic).Dump();
//私有方法传参调用
object[] parammeter={"xie"};
method.Invoke(obj,parammeter).Dump();
}
public class StockClass
{
StockClass(){
}
//字段
static int a;
public int aa;
private int b;
protected int c;
//属性
public int d { get; set; }
public static double e { get; set; }
//方法
private void SayHello(){
Console.WriteLine("Hi!");
}
private string GetStr(string a)
{
return("Hi!"+a);
}
public void SayMoring(){
Console.WriteLine("good Moring!");
}
}