【问题标题】:Using generic interface multiple times on the same class在同一个类上多次使用泛型接口
【发布时间】:2012-07-11 10:46:28
【问题描述】:

我有一个界面

interface IInterface<E>{
    E Foo();
}

然后我创建一个这样的类

class Bar : IInterface<String>, IInterface<Int32> {
}

这实际上效果很好,只是我需要使用显式接口定义两个函数之一,如下所示:

class Bar : IInterface<String>, IInterface<Int32> {
    String Foo();
    Int32 IInterface<Int32>.Foo();
}

缺点是每次我想到达具有显式接口的 Foo() 时都必须进行强制转换。

处理此问题时的最佳做法是什么?

我正在做一个非常依赖性能的应用程序,所以我真的不想每秒进行一百万次投射。这是 JIT 会解决的问题,还是我应该自己存储实例的转换版本?

我没有尝试过这个特定的代码,但它看起来非常接近我正在做的事情。

【问题讨论】:

  • 强制转换几乎没有引用类型的成本。
  • 我的程序每五次加法/乘法就包含一次强制转换。我的假设是加法/乘法是如此便宜,铸造成本变得相当可观。
  • 不比接口调用成本高。

标签: c# generics multiple-inheritance


【解决方案1】:

您不能通过返回类型覆盖,但如果您想避免强制转换,您可以将返回类型转换为 out 参数:

interface IInterface<E> {
    void Foo(out E result);
}

class Bar : IInterface<string>, IInterface<int> {
    public void Foo(out string result) {
        result = "x";
    }
    public void Foo(out int result) {
        result = 0;
    }
}

static void Main(string[] args) {
    Bar b = new Bar();
    int i;
    b.Foo(out i);
    string s;
    b.Foo(out s);
}

【讨论】:

    猜你喜欢
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多