我觉得我的问题非常愚蠢,或者另一种说法是:我在代码中迷失了,现在看到一个解决方法.对问题保持太长时间,你的视力变得更窄更窄> <.另外,我对继承,多态等等还不够好
这是一个想法:我有多个派生类列表,我想在这些列表上调用泛型函数(访问和修改基类的成员).我觉得与继承有关,但我无法让它现在正常运作.
这是我打算做的一个非常简单的例子:
class Baseclass
{
public int ID;
public string Name;
}
class DerivedClass1 : Baseclass
{
}
private void FuncOnBase(List<Baseclass> _collection)
{
// ...
foreach (Baseclass obj in _collection)
{
++obj.ID;
}
// ...
}
private void FuncTest()
{
List<DerivedClass1> collection1 = new List<DerivedClass1>();
collection1.Add(new DerivedClass1() { ID = 1 });
collection1.Add(new DerivedClass1() { ID = 2 });
collection1.Add(new DerivedClass1() { ID = 3 });
FuncOnBase(collection1); // ==> forbidden, cannot convert the derived class list to the …Run Code Online (Sandbox Code Playgroud)