c# - C# 泛型可以这么酷吗?

标签 c# generics overloading

我希望能够做这样的事情:

class A<T1, T2>
{
    public void Call(T1 arg1, T2 arg2)
    {
        B b = new B();
        b.DoSomething(arg1); // determine which overload to use based on T1
        b.DoSomething(arg2); // and T2
    }
}   

class B
{
    public void DoSomething(int x)
    {
        // ...
    }

    public void DoSomething(float x)
    {
       // ...
    }
}

我知道这可以通过 if/else 检查来完成,但这似乎不太优雅,尤其是当我有 20 多种类型可供选择时。

最佳答案

如果你想要类型安全,你能做的最好的可能是:

class A<T1, T2>
{
    public void Call<T>(T1 arg1, T2 arg2) where T : IDoSomething<T1>, IDoSomething<T2>, new()
    {
        T b = new T();
        b.DoSomething(arg1);
        b.DoSomething(arg2);
    }
}

public interface IDoSomething<T>
{
    void DoSomething(T arg);
}

public class B : IDoSomething<int>, IDoSomething<float>
{
    void IDoSomething<int>.DoSomething(int arg)
    {
        Console.WriteLine("Got int {0}", arg);
    }

    void IDoSomething<float>.DoSomething(float arg)
    {
        Console.WriteLine("Got float {0}", arg);
    }
}

你可以像这样使用:

var a = new A<int, float>();
a.Call<B>(1, 4.0f);

关于c# - C# 泛型可以这么酷吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21413660/

相关文章:

c# - 动态 CSV 文件下载

java - 为什么在泛型中需要 "? extends"

java - 在 Spring 4 中干燥一个通用的 RedisTemplate

ios - 我怎样才能在 Swift 5.1 (Xcode 11 Playground) 中为可选项实现泛型和非泛型函数签名的重载?

c# - 如果委托(delegate)不能重载,那么 'Func' 和 'Action' 如何有 16 个重载?

java - 方法不明确

c# - 如何在 C# 中解析示例字符串

c# - 如何下载没有依赖项的nuget包?

c# - 在c#中更改FileStream的长度

ArrayList 数组的 Java 泛型未经检查的转换警告