C# 转换列表<;DerivedClass>;列出<;基类>;
虽然我们可以从基类/接口继承,但为什么我们不能声明一个C# 转换列表<;DerivedClass>;列出<;基类>;,c#,list,inheritance,collections,covariance,C#,List,Inheritance,Collections,Covariance,虽然我们可以从基类/接口继承,但为什么我们不能声明一个列表 使用相同的类/接口 interface A { } class B : A { } class C : B { } class Test { static void Main(string[] args) { A a = new C(); // OK List<A> listOfA = new List<C>(); // compiler Error
列表
使用相同的类/接口
interface A
{ }
class B : A
{ }
class C : B
{ }
class Test
{
static void Main(string[] args)
{
A a = new C(); // OK
List<A> listOfA = new List<C>(); // compiler Error
}
}
接口A
{ }
B类:A
{ }
丙类:乙类
{ }
课堂测试
{
静态void Main(字符串[]参数)
{
A=新的C();//确定
List listOfA=new List();//编译器错误
}
}
有办法吗?因为C不允许这种类型的继承转换。因为C不允许这种类型的继承转换。实现这一点的方法是迭代列表并强制转换元素。这可以使用ConvertAll完成:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
List listOfA=new List().ConvertAll(x=>(A)x);
您还可以使用Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
List listOfA=new List().Cast().ToList();
实现此功能的方法是迭代列表并强制转换元素。这可以使用ConvertAll完成:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
List listOfA=new List().ConvertAll(x=>(A)x);
您还可以使用Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
List listOfA=new List().Cast().ToList();
首先,停止使用不可能理解的类名,如A、B、C。使用动物、哺乳动物、长颈鹿或食物、水果、橘子或关系明确的东西
那么你的问题是:“既然我可以将长颈鹿分配给动物类型变量,为什么我不能将长颈鹿列表分配给动物类型变量?”
答案是:假设你可以。那么会出什么问题呢
嗯,你可以在动物列表中添加一只老虎。假设我们允许您将一个长颈鹿列表放入一个变量中,该变量包含一个动物列表。然后你试着在列表中添加一只老虎。会发生什么?你想让长颈鹿的名单上有一只老虎吗?你想撞车吗?或者,您希望编译器首先通过使赋值非法来保护您免受崩溃的影响吗
我们选择后者
这种转换称为“协变”转换。在C#4中,我们将允许您在已知转换总是安全的情况下对接口和委托进行协变转换。有关详细信息,请参阅我关于协方差和逆变换的博客文章。(本周星期一和星期四都会有一个新的主题。)首先,停止使用不可能理解的类名,如a、B、C。使用动物、哺乳动物、长颈鹿或食物、水果、橘子或其他关系明确的东西 那么你的问题是:“既然我可以将长颈鹿分配给动物类型变量,为什么我不能将长颈鹿列表分配给动物类型变量?” 答案是:假设你可以。那么会出什么问题呢 嗯,你可以在动物列表中添加一只老虎。假设我们允许您将一个长颈鹿列表放入一个变量中,该变量包含一个动物列表。然后你试着在列表中添加一只老虎。会发生什么?你想让长颈鹿的名单上有一只老虎吗?你想撞车吗?或者,您希望编译器首先通过使赋值非法来保护您免受崩溃的影响吗 我们选择后者
这种转换称为“协变”转换。在C#4中,我们将允许您在已知转换总是安全的情况下对接口和委托进行协变转换。有关详细信息,请参阅我关于协方差和逆变换的博客文章。(本周星期一和星期四都会有一个关于这个主题的新主题。)至于为什么它不起作用,理解它可能会有所帮助 为了说明为什么这不起作用,下面是对您提供的代码的更改:
void DoesThisWork()
{
List<C> DerivedList = new List<C>();
List<A> BaseList = DerivedList;
BaseList.Add(new B());
C FirstItem = DerivedList.First();
}
void完成这项工作()
{
List DerivedList=新列表();
List BaseList=衍生列表;
添加(新的B());
C FirstItem=DerivedList.First();
}
这样行吗?列表中的第一项为“B”类型,但派生列表项的类型为C
现在,假设我们真的只想创建一个通用函数,该函数在实现a的某个类型的列表上运行,但我们不关心它是什么类型:
void ThisWorks<T>(List<T> GenericList) where T:A
{
}
void Test()
{
ThisWorks(new List<B>());
ThisWorks(new List<C>());
}
void ThisWorks(列表GenericList),其中T:A
{
}
无效测试()
{
ThisWorks(新列表());
ThisWorks(新列表());
}
至于它为什么不起作用,理解它可能会有所帮助
为了说明为什么这不起作用,下面是对您提供的代码的更改:
void DoesThisWork()
{
List<C> DerivedList = new List<C>();
List<A> BaseList = DerivedList;
BaseList.Add(new B());
C FirstItem = DerivedList.First();
}
void完成这项工作()
{
List DerivedList=新列表();
List BaseList=衍生列表;
添加(新的B());
C FirstItem=DerivedList.First();
}
这样行吗?列表中的第一项为“B”类型,但派生列表项的类型为C
现在,假设我们真的只想创建一个通用函数,该函数在实现a的某个类型的列表上运行,但我们不关心它是什么类型:
void ThisWorks<T>(List<T> GenericList) where T:A
{
}
void Test()
{
ThisWorks(new List<B>());
ThisWorks(new List<C>());
}
void ThisWorks(列表GenericList),其中T:A
{
}
无效测试()
{
ThisWorks(新列表());
ThisWorks(新列表());
}
如果改用IEnumerable
,它会工作(至少在C#4.0中,我还没有尝试过以前的版本)。这只是一个演员阵容,当然,它仍然是一个列表
而不是-
List listOfA=new List();//编译器错误
在问题的原始代码中,使用-
IEnumerable listOfA=new List();//编译器错误-不再有!:)
如果改用IEnumerable
,它会工作(至少在C#4.0中,我还没有尝试过以前的版本)。这只是一个演员阵容,当然,它仍然是一个列表
而不是-
List listOfA=new List();//编译器错误
在问题的原始代码中,使用-
IEnumerable listOfA=new List();//编译器错误-不再有!:)代码>引用Eric的精彩解释
会发生什么?你想让长颈鹿的名单上有一只老虎吗?你想撞车吗?还是希望编译器通过使赋值为illega来防止崩溃
List<string> listString=new List<string>();
List<object> listObject=(List<object>)listString;//Assume that this is possible
listObject.Add(new object());
public static List<TTo> Cast<TFrom, TTo>(List<TFrom> fromlist)
where TFrom : class
where TTo : class
{
return fromlist.ConvertAll(x => x as TTo);
}
using System.Runtime.CompilerServices;
...
class Tool { }
class Hammer : Tool { }
...
var hammers = new List<Hammer>();
...
var tools = Unsafe.As<List<Tool>>(hammers);
List<Tiger> myTigersList = new List<Tiger>() { new Tiger(), new Tiger(), new Tiger() };
List<Animal> myAnimalsList = myTigersList; // Compiler error
Tiger[] myTigersArray = new Tiger[3] { new Tiger(), new Tiger(), new Tiger() };
Animal[] myAnimalsArray = myTigersArray; // No problem
myAnimalsArray[1] = new Giraffe();
using System;
using System.Collections.Generic;
using System.Linq;
interface IAnimal
{
public string Name { get; }
}
class Bear : IAnimal
{
public string BearName = "aBear";
public string Name => BearName;
}
class Cat : IAnimal
{
public string CatName = "aCat";
public string Name => CatName;
}
// Dog has no base class/interface; it isn't related to the other classes
class Dog
{
public string DogName = "aDog";
public string Name => DogName;
}
public class AssignDerivedClass
{
public static void TestDynamicListAndArray()
{
dynamic any = new List<Bear>() // List of derived
{
new Bear() { BearName = "Bear-1" },
new Bear() { BearName = "Bear-2" }
};
//any[0].CatName = "NewCat"; // => Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
Console.WriteLine($"Bear names: {any[0].BearName}, {Name(any[1])}");
any = new Cat[] // Array of derived
{
new Cat() { CatName = "Cat-3" },
new Cat() { CatName = "Cat-4" }
};
Console.WriteLine($"Cat names: {any[0].CatName}, {any[1].Name}");
any = new List<Dog>() // List of non-related class
{
new Dog() { DogName = "Dog-5" },
new Dog() { DogName = "Dog-6" }
};
Console.WriteLine($"Dog names: {any[0].DogName}, {Name(any[1])}");
any = new List<IAnimal>() // List of interface
// any = new IAnimal[] // Array of interface works the same
{
new Bear() { BearName = "Bear-7" },
new Cat() { CatName = "Cat-8" }
};
Console.WriteLine($"Animal names: {any[0].BearName}, {any[1].CatName}");
any[0].BearName = "NewBear";
Console.WriteLine($"Animal names: {Name(any[0])}, {any[1].Name}");
}
private static string Name(dynamic anymal)
{
return anymal switch
{
Bear bear => bear.BearName,
Cat cat => cat.CatName,
Dog dog => dog.DogName,
_ => "No known Animal"
};
}
// Bear names: Bear-1, Bear-2
// Cat names: Cat-3, Cat-4
// Dog names: Dog-5, Dog-6
// Animal names: Bear-7, Cat-8
// Animal names: NewBear, Cat-8
}
public static void TestArray()
{
Bear[] bears = { new Bear(), null };
IAnimal[] bearAnimals = bears;
//bearAnimals[1] = new Cat(); // System.ArrayTypeMismatchException
bearAnimals[1] = new Bear() { BearName = "Bear-1" };
Console.WriteLine($"Bear names: {bearAnimals[0].Name}, {bears[1].BearName}");
}
// Result => Bear names: aBear, Bear-1
public static void TestIEnumerableAndIReadonlyList()
{
var cats = new List<Cat>()
{
new Cat() { CatName = "Cat-3" },
new Cat() { CatName = "Cat-4" }
};
IEnumerable<IAnimal> iEnumerable = cats;
Console.WriteLine($"Cat names: {(iEnumerable.ElementAt(0) as Cat).CatName}, "
+ Name(iEnumerable.Last()));
IReadOnlyList<IAnimal> iROList = cats;
Console.WriteLine($"Cat names: {iROList[0].Name}, {Name(iROList[1])}");
//iROList.Add(new Cat()); // compiler error CS61: no definition for 'Add'
}
// Result:
// Cat names: Cat-3, Cat-4
// Cat names: Cat-3, Cat-4
public static void TestListOfInterface()
{
var bears = new List<IAnimal>()
{
new Bear() { BearName = "Bear-1" },
new Cat() { CatName = "Cat-3" },
};
bears.Add(new Bear() { BearName = "Bear-2" });
string bearNames = string.Join(", ", bears.Select(animal => animal.Name));
Console.WriteLine($"Bear names: {bearNames}");
string bearInfo0 = VerifyBear(bears[0]);
string bearInfo1 = VerifyBear(bears[1]);
Console.WriteLine($"One animal is {bearInfo0}, the other one is {bearInfo1}");
string VerifyBear(IAnimal bear)
=> (bear as Bear)?.BearName ?? "disguised as a bear!!!";
}
// Bear names: Bear-1, Cat-3, Bear-2
// One animal is Bear-1, the other one is disguised as a bear!!!