1,C#中无法访问类中私有成员函数吗?函数“private void AcceptDetails()"可以改成”public void AcceptDetails()“可以进行,但是在”private"情况下,如何调用函数呢?
2, 代码如下:
using System;
namespace RectangleApplication
{
class Rectangle
{
private double length;
private double width;
private void AcceptDetails()
{
Console.WriteLine("Please input length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please input width: ");
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("length; {0}", length);
Console.WriteLine("width: {0}", width);
Console.WriteLine("area: {0}", GetArea());
}
}
class ExecuteRetangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.AcceptDetails();
r.Display();
Console.ReadLine();
}
}
}
反射调用
https://blog.csdn.net/chenbeifang/article/details/99725025
新增一个public方法直接调用它.........
class Rectangle
{
public void acc() {
AcceptDetails();
}
}
反射
Rectangle rec = new Rectangle();
Type t = typeof(Rectangle);
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
MethodInfo mInfo = t.GetMethod("AcceptDetails",flags);
ConstructorInfo magicConstructor = t.GetConstructor(Type.EmptyTypes);
mInfo.Invoke(rec, null);
rec.Display();
Console.ReadLine();