带通用参数的接口与带通用方法的接口

带通用参数的接口与带通用方法的接口

本文介绍了带通用参数的接口与带通用方法的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的界面和具体的实现方式

Let's say I have such interface and concrete implementation

public interface IMyInterface<T>
{
    T My();
}

public class MyConcrete : IMyInterface<string>
{
    public string My()
    {
        return string.Empty;
    }
}

所以我为字符串,对于 int 我可以有一个更具体的实现。没关系。但是,让我们说,我想做同样的事情,但是要使用通用方法,所以我有

So I create MyConcrete implementation for strings, I can have one more concrete implementation for int. And that's ok. But let's say, that I want to do the same thing, but with generic methods, so I have

public interface IMyInterface2
{
    T My<T>();
}

public class MyConcrete2 : IMyInterface2
{
    public string My<string>()
    {
        throw new NotImplementedException();
    }
}

所以我有相同的 IMyInterface2 ,但它通过 T My< T>()定义了通用行为。在我的具体类中,我想实现 My 行为,但是对于具体的数据类型- string 。但是C#不允许我这样做。

So I have the same IMyInterface2, but which defines generic behavior by means of T My<T>(). In my concrete class I want to implement My behavior, but for concrete data type - string. But C# doesn't allow me to do that.

我的问题是为什么我不能这样做?
换句话说,如果我可以将 MyInterface< T> 的具体实现创建为 MyClass:MyInterface< string> 并在这一点上停止通用性,为什么我不能使用通用方法- T My&T;(()

My question is why I cannot do that?In other words, if i can create concrete implementation of MyInterface<T> as MyClass : MyInterface<string> and stop genericness at this point, why I can't do that with generic method - T My<T>()?

推荐答案

您的通用方法实现也必须是通用的,因此必须是:

Your generic method implementation has to be generic as well, so it has to be:

public class MyConcrete2 : IMyInterface2
{
    public T My<T>()
    {
        throw new NotImplementedException();
    }
}

为什么不能做我的< string>()在这里?由于接口协定需要一种方法,因此可以使用任何类型参数 T 进行调用,而您必须履行该协定。

Why you can't do My<string>() here? Because interface contract needs a method, that could be called with any type parameter T and you have to fulfill that contract.

为什么此时您不能停止通用性,因为这会导致如下情况:

Why you can't stop genericness in this point? Because it would cause situations like following:

类声明:

public interface IMyInterface2
{
    T My<T>(T value);
}

public class MyClass21 : IMyInterface2
{
    public string My<string>(string value) { return value; }
}

public class MyClass22 : IMyInterface2
{
    public int My<int>(int value) { return value; }
}

用法:

var item1 = new MyClass21();
var item2 = new MyClass22();

// they both implement IMyInterface2, so we can put them into list
var list = new List<IMyInterface2>();
list.Add(item1);
list.Add(item2);

// iterate the list and call My method
foreach(IMyInterface2 item in list)
{
    // item is IMyInterface2, so we have My<T>() method. Choose T to be int and call with value 2:
    item.My<int>(2);

    // how would it work with item1, which has My<string> implemented?
}

这篇关于带通用参数的接口与带通用方法的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:34