C# 在运行时从泛型类型查找方法重载

标签 c# generics methods overloading

考虑以下方法:

public void foo(int a) {
   //do something with a
}

public void foo(ushort a) {
   //do something with a
}

public void foo<T>(Nullable<T> a) where T : struct {
     if (!a.HasValue) {
        return;
     }

     foo(a.Value); //find appropriate method based on type of a?
}

有没有办法根据参数的泛型类型找到相应的方法来调用?例如,如果 (T)a 是 int,则调用第一个方法,如果它是 ushort,则调用第二个方法。如果没有这样的方法超过,可能会抛出运行时异常。

我尝试过以下方法:

public void foo<T>(Nullable<T> a) where T : struct {
     if (!a.HasValue) {
        return;
     }
     switch(a.Value.GetType()) {
           case typeof(int): foo((int)a.Value); break;
           case typeof(ushort): foo((ushort)a.Value); break;
           //and so on
     }
}

但是编译器不喜欢强制转换(“无法将类型 T 转换为 int”);有什么办法可以实现我想要做的事情吗?

最佳答案

尝试

public void foo<T>(Nullable<T> a) where T : struct {
 if (!a.HasValue) {
    return;
 }

 foo((dynamic)a.Value);
}

a.Value 的类型将在运行时使用 dynamic 进行解析,并调用适当的重载。

关于C# 在运行时从泛型类型查找方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18709069/

相关文章:

c# - 全局更改 MVC 中生成的 URL

swift - 有条件的协议(protocol)符合协议(protocol)

python - python中嵌套函数(函数中的函数)的目的

java - 我父级的类方法没有接收我的实例变量值

c# - 以编程方式添加 Adomd 参数 C#

c# - 有什么方法可以在配置而不是代码中设置 Web 服务的命名空间?

c# - SQL返回列中具有最大值的行,在特定范围内

c# - 在泛型方法中返回一个类的对象

c# - 为什么类类型参数的方差必须与其方法的返回/参数类型参数的方差匹配?

android - 在android按钮上调用方法点击