接口的协方差问题导致来回转换

时间:2013-08-28 17:45:10

标签: c# .net-3.5 covariance

我坚持使用.NET 3.5来处理我正在进行的项目。我正在遇到一个轻微但令人讨厌的协方差问题。这与我目前的模式类似:

public interface ISupportSomething<T> where T : struct
{
    T StructProperty { get; set; }
}

public class SupportSomething : ISupportSomething<int>
{
    public int StructProperty { get; set; }
}

public static class ISupportSomethingExtensions
{
    public static IEnumerable<ISupportSomething<T>> Method<T>
            (this IEnumerable<ISupportSomething<T>> collection)
    {
        return null;
    }
}

public class SupportTester
{
    private void SomeMethod()
    {
        IEnumerable<SupportSomething> source;

        // invalid, i would generally fix this with a covariant
        // declaration: ISupportSomething<out T>
        var methodResult1 = source.Method();

        // valid
        var methodResult2 = source.Cast<ISupportSomething<int>>().Method();

        // this means that if i want to make a function that
        // returns an IEnumerable<SupportSomething> that
        // has called ISupportSomethingExtensions.Method i
        // have to do this cast back and forth approach

    }

    // here is a similar function to what i have that showcases the ugliness
    // of calling this extension method
    private IEnumerable<SupportSomething> SomeFunction()
    {
        IEnumerable<SupportSomething> source;

        var tempSourceList = source.Cast<ISupportSomething<int>>();

        tempSourceList = tempSourceList.Method();

        return tempSourceList; // invalid
        return tempSourceList.Cast<SupportSomething>(); //valid
    }
}

我的问题相当简单,我想我已经知道了答案,但是:在使用.NET 3.5时,有没有办法在处理这些对象时不必进行反复播放(参见上一个函数)? / p>

我猜我运气不好并且必须这样做,因为在.NET 4.0之前没有对协方差的通用支持。

1 个答案:

答案 0 :(得分:0)

您可以像这样修改扩展方法:

public static class ISupportSomethingExtensions
{
    public static IEnumerable<T1> Method<T1, T2>
            (this IEnumerable<T1> collection)
        where T1 : ISupportSomething<T2>
        where T2 : struct
    {
        return null;
    }
}

现在它不需要依赖IEnumerable协变来工作。

此更改的不幸网站效果是Method将无法再推断出它的通用参数,您需要明确列出:

private IEnumerable<SupportSomething> SomeFunction()
{
    IEnumerable<SupportSomething> source = Enumerable.Empty<SupportSomething>();

    return source.Method<SupportSomething, int>();
}