C# 利用反射模拟多态效果
public class A
{
}
public class B : A
{
}
public class C : A
{
}
public static class Extension
{
public static void Test(B b)
{
Console.WriteLine("this is B");
}
public static void Test(A a)
{
Console.WriteLine("this is A");
}
public static void Test(C c)
{
Console.WriteLine("this is C");
}
}
internal class Program
{
static void ReflectInvoke(List<A> objs)
{
MethodInfo[] mis = (from method in typeof(Extension).GetMethods()
where method.Name == "Test"
select method).ToArray();
foreach (var a in objs)
{
foreach (var m in mis)
{
if (m.GetParameters().First().ParameterType.Name == a.GetType().Name)
{
m.Invoke(null, new object[] { a });
break;
}
}
}
}
}
output:
this is A
this is B
this is C
#####
愿你一寸一寸地攻城略地,一点一点地焕然一新
#####