我被困在我正在从事的项目中使用 .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,在处理这些对象时不必来回转换(参见最后一个函数)?
我猜我运气不好,不得不这样做,因为在 .NET 4.0 之前没有对协方差的通用支持。