我试图向某人展示接口在他们创建的疯狂情况下的用法。他们在列表中有几个不相关的对象,需要对每个对象中的两个字符串属性执行操作。我指出,如果它们将属性定义为接口的一部分,则可以使用接口对象作为对其起作用的方法参数的类型;例如:
void PrintProperties(IEnumerable<ISpecialProperties> list)
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}
这似乎很好,但是需要处理的列表没有(也不应该)使用接口作为类型参数来声明。然而,似乎不能转换成不同的类型参数。例如,这失败了,我不明白为什么:
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Test> myList = new List<Test>();
for (int i = 0; i < 5; i++)
{
myList.Add(new Test());
}
PrintList((IEnumerable<IDoSomething>)myList);
}
static void PrintList(IEnumerable<IDoSomething> list)
{
foreach (IDoSomething item in list)
{
item.DoSomething();
}
}
}
interface IDoSomething
{
void DoSomething();
}
public class Test : IDoSomething
{
public void DoSomething()
{
Console.WriteLine("Test did it!");
}
}
}
发布于 2018-08-07 09:46:59
问题在于方法,而不是它的名称.
void PrintProperties<SP>(IEnumerable<SP> list) where SP: ISpecialProperties
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}
发布于 2018-08-07 10:29:08
它失败的原因是泛型在C#(尚未)中没有表现出差异。
至于对IEnDigable的修复<T>然而,试着这样做:
public static IEnumerable<TBase> SafeConvert<TBase, TDerived>(IEnumerable<TDerived> source)
where TDerived : TBase
{
foreach (TDerived element in source)
{
yield return element; // Implicit conversion to TBase
}
}
https://stackoverflow.com/questions/-100000510
复制相似问题