使用反射
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;//需加入此名字空间
namespace ConsoleApplication2
{
class CComand
{
private bool m_bIsRunning = false;
public bool StartRun(string sUserName)
{
Console.WriteLine("Device:启动设备,操作员:{0}", sUserName);
if (m_bIsRunning)
{
Console.WriteLine("Device:设备已经启动,不能重复启动。");
return false;
}
else
{
m_bIsRunning = true;
Console.WriteLine("Device:设备已经成功启动。");
return true;
}
}
public bool StopRun(string sUserName)
{
Console.WriteLine("Device:启动设备,操作员:{0}", sUserName);
if (!m_bIsRunning)
{
Console.WriteLine("设备已经停止,不能重复停止。");
return false;
}
else
{
m_bIsRunning = false;
Console.WriteLine("设备成功停止!");
return true;
}
}
}
class Program
{
static void Main(string[] args)
{
CComand cmd = new CComand();
Type objType = cmd.GetType();
MethodInfo mi = objType.GetMethod("StartRun");
bool ret = (bool)mi.Invoke(cmd, new object[] { "张三" });//这里第二个参数是一个对象数组,对应方法中的参数列表
if (ret)
Console.WriteLine("启动成功!");
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;//需加入此名字空间
namespace ConsoleApplication2
{
class CComand
{
private bool m_bIsRunning = false;
public bool StartRun(string sUserName)
{
Console.WriteLine("Device:启动设备,操作员:{0}", sUserName);
if (m_bIsRunning)
{
Console.WriteLine("Device:设备已经启动,不能重复启动。");
return false;
}
else
{
m_bIsRunning = true;
Console.WriteLine("Device:设备已经成功启动。");
return true;
}
}
public bool StopRun(string sUserName)
{
Console.WriteLine("Device:启动设备,操作员:{0}", sUserName);
if (!m_bIsRunning)
{
Console.WriteLine("设备已经停止,不能重复停止。");
return false;
}
else
{
m_bIsRunning = false;
Console.WriteLine("设备成功停止!");
return true;
}
}
}
class Program
{
static void Main(string[] args)
{
CComand cmd = new CComand();
Type objType = cmd.GetType();
MethodInfo mi = objType.GetMethod("StartRun");
bool ret = (bool)mi.Invoke(cmd, new object[] { "张三" });//这里第二个参数是一个对象数组,对应方法中的参数列表
if (ret)
Console.WriteLine("启动成功!");
Console.ReadLine();
}
}
}