c# java 重载操作符,如何以编程方式在C#中执行方法重载解析?

本文详细介绍了如何使用C#中的Type.GetMethod方法来解析方法重载。通过示例展示了如何根据参数类型获取特定的方法实例,包括处理params参数、派生类、委托以及接口实现的情况。这种方法的强大之处在于其能够正确解析复杂重载,即使在不预期的情况下也能工作。
摘要由CSDN通过智能技术生成

答案

使用 Type.GetMethod(String name, Type[] types) 进行编程重载解析 . 这是一个例子:

MethodInfo methodToInvoke = typeof(MyClass)

.GetMethod("myFunc", new System.Type[] { typeof(BaseClass) });

解释

在示例中, methodToInvoke 将是 myFunc(BaseClass bc) 而不是 myFunc(DerivedClass dc) ,因为 types 数组指定要获取的方法的参数列表 .

From the MSDN documentation, Type.GetMethod(String name, Type[] types) 有两个参数:

name 是要获取的方法的名称,和

types 提供方法参数的顺序,数量和类型 .

运行代码

using System;

using System.Reflection;

public static class Program

{

public static void Main()

{

MethodInfo methodToInvoke = typeof(MyClass)

.GetMethod("myFunc", new System.Type[] { typeof(BaseClass) });

var result = methodToInvoke

.Invoke(new MyClass(), new object[] { new BaseClass() });

Console.WriteLine(result);

}

public class MyClass

{

public static string myFunc(BaseClass bc) {

return "BaseClass";

}

public static string myFunc(DerivedClass dc) {

return "DerivedClass";

}

}

public class BaseClass { }

public class DerivedClass : BaseClass { }

}

输出为 BaseClass .

编辑:这很强大 .

GetMethod 解析了采用 params ,更多派生类,委托和接口实现的方法 . This Fiddle demonstrates all of those cases . 这是电话和他们检索的内容 .

与params一起使用

MethodInfo methodToInvoke2 = typeof(MyClass).GetMethod(

"myFunc",

new System.Type[] { typeof(Int32[]) });

将解决此方法

public static string myFunc(params int[] i)

{

return "params";

}

适用于更多派生类

MethodInfo methodToInvoke3 = typeof(MyClass).GetMethod(

"myFunc",

new System.Type[] { typeof(MoreDerivedClass) });

解决了一个占用 MoreDerivedClass 的方法

public class BaseClass { }

public class DerivedClass : BaseClass { }

public class MoreDerivedClass : DerivedClass {}

与代表合作

MethodInfo methodToInvoke4 = typeof(MyClass).GetMethod(

"myFunc",

new System.Type[] { typeof(MyDelegate) });

...将检索获取此委托的方法:

public delegate void MyDelegate(string x);

适用于接口实现

MethodInfo methodToInvoke5 = typeof(MyClass).GetMethod(

"myFunc",

new System.Type[] { typeof(MyImplementation) });

...成功检索一个需要 MyImplementation 的方法

public interface IMyInterface {}

public class MyImplementation : IMyInterface {}

因此,它是健壮的,我们可以使用 GetMethod 在我们可能不期望工作的情况下执行重载解析 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值