基本上就可以……
理由:因为两者的实现在你的代码中可以看出,只用到了参数的迭代器的特性,“最小匹配”原则一下,你可以将其指定为IEnumerable。如果有其他需求,可以再放宽要求。
测试:
class GenericClass
{
public static void ListDelete1<T>(T list) where T : IEnumerable<IDB>
{
foreach (IDB item in list)
{
item.Delete();
}
}
public static void ListDelete2<T>(IEnumerable<T> list) where T : IDB
{
foreach (T item in list)
{
item.Delete();
}
}
public static void ListDelete3<T>(T list) where T : IEnumerable
{
foreach (IDB item in list)
{
if (item is IDB)
(item as IDB).Delete();
//if (i is OtherInterface)
// (item as OtherInterface).Delete();
}
}
public interface IDB
{
//Other members
void Delete();
}
public class BaseDT:IDB
{
public void Delete() { Console.WriteLine("succeed delete!"); }
}
class Program
{
static void Main(string[] args)
{
List<GenericClass.IDB> list1 = new List<GenericClass.IDB>();
list1.Add(new GenericClass.BaseDT());
list1.Add(new GenericClass.BaseDT());
list1.Add(new GenericClass.BaseDT());
list1.Add(new GenericClass.BaseDT());
GenericClass.ListDelete1<IEnumerable<GenericClass.IDB>>(list1);
Console.WriteLine("========================");
GenericClass.IDB[] list2 = new GenericClass.IDB[] { new GenericClass.BaseDT(), new GenericClass.BaseDT(), new GenericClass.BaseDT() };
GenericClass.ListDelete1<IEnumerable<GenericClass.IDB>>(list2);
Console.WriteLine("========================");
List<GenericClass.IDB> list3 = new List<GenericClass.IDB>();
list3.Add(new GenericClass.BaseDT());
list3.Add(new GenericClass.BaseDT());
list3.Add(new GenericClass.BaseDT());
list3.Add(new GenericClass.BaseDT());
GenericClass.ListDelete2<GenericClass.IDB>(list3);
Console.WriteLine("========================");
GenericClass.IDB[] list4 = new GenericClass.IDB[] { new GenericClass.BaseDT(), new GenericClass.BaseDT(), new GenericClass.BaseDT() };
GenericClass.ListDelete2<GenericClass.IDB>(list4);
Console.WriteLine("========================");
List<GenericClass.IDB> list5 = new List<GenericClass.IDB>();
list5.Add(new GenericClass.BaseDT());
list5.Add(new GenericClass.BaseDT());
list5.Add(new GenericClass.BaseDT());
list5.Add(new GenericClass.BaseDT());
GenericClass.ListDelete3<IEnumerable>(list5);
Console.WriteLine("========================");
GenericClass.IDB[] list6 = new GenericClass.IDB[] { new GenericClass.BaseDT(), new GenericClass.BaseDT(), new GenericClass.BaseDT() };
GenericClass.ListDelete3<IEnumerable>(list6);
}
}
其实上面的方法也是可以的,只要你对实现IDB的方法实现自己特殊的部分,比如说:
public sealed class ClassA : IDB
{
public string X {get;set;}
public string Y {get;set;}
public string IDB.GetResult()
{
return (X+Y);
}
public sealed class ClassB : IDB
{
public string X {get;set;}
public string IDB.GetResult()
{
return X;
}
}
}
这样,你统一调用Response.Write(IDB.GetResult());就可以了
这就是最基本的多态啦撒……