110,538
社区成员
发帖
与我相关
我的任务
分享
public interface IInterface
{
string Name { get; set; }
}
public class ClassA : IInterface
{
#region IInterface Members
public string Name
{
get;
set;
}
#endregion
}
static void Main(string[] args)
{
IList<ClassA> classes=new List<ClassA>();
classes.Add(new ClassA(){Name="Abc"});
IList<IInterface> tmp = classes.Cast<IInterface>().ToList();
List<ClassA> converted=tmp.Cast<ClassA>().ToList();
converted.ForEach(t => Console.WriteLine(t.Name));
Console.Read();
}
List<int> ints = new List<int>();
ints.Add(1);
ints.Add(10);
ints.Add(42);
List<object> objects = new List<object>();
// doesnt compile ints is not a IEnumerable<object>
//objects.AddRange(ints);
// Simple workaround for single method
// Variance in one direction only
public static void Add<S, D>(List<S> source, List<D> destination)
where S : D
{
foreach (S sourceElement in source)
{
destination.Add(sourceElement);
}
}
// does compile
VarianceWorkaround.Add<int, object>(ints, objects);
IList <IInterface1> ls=new IList <Class1>();
IInterface1 obj=(IInterface1)Class1Obj;