本帖最后由 李维强-15级 于 2017-9-25 05:35 编辑
http://www.cnblogs.com/wangshenhe/p/3256657.html
下面是应用
通过函数名字符串执行相应的函数,用反射
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode using System;
namespace Ref
{
class Program
{
static void Main(string[] args)
{
SayHello obj = new SayHello();
Type type = typeof(SayHello);
type.GetMethod("Say").Invoke(obj, new object[0]);
Console.ReadKey(true);
}
}
class SayHello
{
public void Say()
{
Console.WriteLine("Hello World!");
}
}
}
这里用委托
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode using System;
namespace Ref
{
delegate void dgtSayHello();
class Program
{
static void Main(string[] args)
{
SayHello obj = new SayHello();
obj.GetSayHello("SayCn")();
Console.ReadKey(true);
}
}
class SayHello
{
public void Say()
{
Console.WriteLine("Hello World!");
}
public void SayCn()
{
Console.WriteLine("世界你好!");
}
public void SayUs()
{
Console.WriteLine("Hello World!");
}
public dgtSayHello GetSayHello(string methodName)
{
switch (methodName)
{
case "SayCn":
return new dgtSayHello(this.SayCn);
case "SayUs":
return new dgtSayHello(this.SayUs);
default:
return new dgtSayHello(this.Say);
}
}
}
} |