如何从 C# 中的抽象列表访问派生 class 的成员变量
How to access member variable of derived class from an abstract list in C#
这是基础代码 class:
public abstract class baseClass
{
public string Name { get; set; }
}
然后有两个派生classes
public derived1: baseClass
{
public int derivedMemberVariable { get; set; }
}
public derived2: baseClass
{
public string derivedMemberVariableAlternative { get; set; }
}
然后我创建了一个基本列表 class 并向其中添加了两个派生类型:
List<baseClass> baseList = new List<baseClass>();
derived1 der1 = new derived1{
Name = "Derived1 Name",
derivedMemberVariable = 10
};
derived2 der2 = new derived2{
Name = "Derived2 Name",
derivedMemberVariable = "STRING"
};
baseList.Add(der1);
baseList.Add(der2);
foreach (b in baseList){
b.derivedMemberVariable //this is what fails
}
如何从使用基 class 创建的列表中访问这个派生成员变量??
我必须按原样使用代码,因为它用于学校项目,所以我无法修改 classes 的工作方式,但我想我可以修改列表?但该列表需要包含两个派生的 classes。
我是否能够完成此任务,或者我必须采取其他方法吗?
好的,所以出于某种原因,这次我一尝试投射就成功了!我觉得很蠢:/
感谢 AntiTcb 指出。
我最后做的是:
foreach (b in baseList){
if(b.GetType() == der1.GetType()){
var q = b as derived1;
q.derivedMemberVariable; // now works
}
if(b.GetType() == der2.GetType()){
var q = b as derived2;
q.derivedMemberVariableAlternative; // now works
}
}
使用模式匹配:
foreach (b in baseList){
{
if(b is DerivedType d)
{
d.derivedMemberVariable //this is what fails
}
}
这是基础代码 class:
public abstract class baseClass
{
public string Name { get; set; }
}
然后有两个派生classes
public derived1: baseClass
{
public int derivedMemberVariable { get; set; }
}
public derived2: baseClass
{
public string derivedMemberVariableAlternative { get; set; }
}
然后我创建了一个基本列表 class 并向其中添加了两个派生类型:
List<baseClass> baseList = new List<baseClass>();
derived1 der1 = new derived1{
Name = "Derived1 Name",
derivedMemberVariable = 10
};
derived2 der2 = new derived2{
Name = "Derived2 Name",
derivedMemberVariable = "STRING"
};
baseList.Add(der1);
baseList.Add(der2);
foreach (b in baseList){
b.derivedMemberVariable //this is what fails
}
如何从使用基 class 创建的列表中访问这个派生成员变量??
我必须按原样使用代码,因为它用于学校项目,所以我无法修改 classes 的工作方式,但我想我可以修改列表?但该列表需要包含两个派生的 classes。
我是否能够完成此任务,或者我必须采取其他方法吗?
好的,所以出于某种原因,这次我一尝试投射就成功了!我觉得很蠢:/
感谢 AntiTcb 指出。
我最后做的是:
foreach (b in baseList){
if(b.GetType() == der1.GetType()){
var q = b as derived1;
q.derivedMemberVariable; // now works
}
if(b.GetType() == der2.GetType()){
var q = b as derived2;
q.derivedMemberVariableAlternative; // now works
}
}
使用模式匹配:
foreach (b in baseList){
{
if(b is DerivedType d)
{
d.derivedMemberVariable //this is what fails
}
}