我想为 ICollection<T2>
提供一个扩展方法女巫回到我身边IReadOnlyCollection<T1>
.我需要所有这些,以免在代码中重复自己。我有以下代码:
public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T1 : T2
{
if (storage.Count > 0)
{
return new List<T1>(storage);
}
else
{
return new List<T1>();
}
}
但遗憾的是它无法编译。 那么让我们看一个更简单的上面的例子:
public interface IDatabase {}
public class Database : IDatabase, IDisposable {}
public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T2 : T1 where T1 : new()
{
// compiles
List<Database> derivedList = new List<PublishedDatabase>();
List<IDatabase> baseList = new List<IPublishedDatabase>(derivedList);
// doesn't compile
// with casting it works
List<T2> derivedListT = new List<T2>();
List<T1> baseList1T = new List<T1>(derivedListT/* as IEnumerable<T1>*/);
//...
}
我可以通过泛型使用嵌套类列表创建基类列表而不进行强制转换吗?
最佳答案
我可能误解了这里的约束条件,但您可以暂时使用 dynamic
来欺骗分析器
public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T2: T1
{
dynamic temp = storage;
return new ReadOnlyCollection<T1>(new List<T1>(temp));
}
...
var list = new List<SomeChild>()
{
new SomeChild()
};
var interfaces = list.All<ISomeBase, SomeChild>();
注意:如果您的代码分析器提示强制转换,您会认为他们会更加提示dynamic
...也完全未经测试,可能有更好的方法来做到这一点
关于c# - 如何通过泛型使用嵌套类列表创建基类列表而不进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335911/