C# 具有公共基类的不同类型的返回列表
我正在设计一个方法,它应该返回一个实例列表,每个实例实际上是不同的数据类型 下面是我的设计草案,我需要一个建议C# 具有公共基类的不同类型的返回列表,c#,oop,generics,C#,Oop,Generics,我正在设计一个方法,它应该返回一个实例列表,每个实例实际上是不同的数据类型 下面是我的设计草案,我需要一个建议 public class abstract Base { //DataType is an enum public abstract DataType Type { get; set; } public abstract BaseType Value { get; set; } } public abstract class BaseType { }
public class abstract Base
{
//DataType is an enum
public abstract DataType Type { get; set; }
public abstract BaseType Value { get; set; }
}
public abstract class BaseType
{
}
public class MyString:BaseType
{
}
public class MyInt:BaseType
{
}
//string for example
public class Type1:Base
{
public override DataType Type
{
get { return DataType.Type1; }
set;
}
public override BaseType Value
{
get { return new MyString("a"); }
set;
}
}
public class Type2:Base
{
public override DataType Type
{
get { return DataType.Type2; }
set;
}
public override BaseType Value
{
//MyInt for example
get { return new MyInt(10); }
set;
}
}
方法应该是
List<Base> GetValues();
List GetValues();
打电话的人应该写这样的东西
List<Base> values = GetValues();
foreach(var value in values)
{
switch(value.Type)
{
case DataType.MyString:
MyString str = value.Value as MyString;
break;
case DataType.MyInt:
MyInt str = value.Value as MyInt;
break;
}
}
List values=GetValues();
foreach(值中的var值)
{
开关(值.类型)
{
case DataType.MyString:
MyString str=value.value作为MyString;
打破
case DataType.MyInt:
MyInt str=value。值为MyInt;
打破
}
}
我的问题是什么是最好的设计?如何更好地使用泛型?我建议使用泛型基类:
public abstract class Base<T>
where T : BaseType
{
public abstract DataType Type { get; }
public abstract T Value { get; set; }
}
public abstract class Base
{
public abstract DataType Type { get; }
}
public abstract class Base<T> : Base
where T : BaseType
{
public abstract T Value { get; set; }
}
如果它返回不同类型的元素,则可以使用另一个非泛型基类:
public abstract class Base<T>
where T : BaseType
{
public abstract DataType Type { get; }
public abstract T Value { get; set; }
}
public abstract class Base
{
public abstract DataType Type { get; }
}
public abstract class Base<T> : Base
where T : BaseType
{
public abstract T Value { get; set; }
}
注意,我将非泛型部分移到了非泛型基类中,这样您仍然可以使用DataType属性
您需要将值强制转换为相应的类型,以便访问值
属性:
List<Base> values = GetValues();
foreach (Base value in values)
{
switch (value.DataType)
{
case DataType.MyString:
MyString myString = value as MyString;
...
case DataType.MyInt:
MyInt myInt = value as MyInt;
...
}
}
我不明白这是怎么回事。。。你能详细说明一下你想要完成什么吗?除非你愿意使用
接口IBase
,并且如果你想让列表包含混合实例,那么你就不能真正做到这一点。当然,接口只能为值指定一个getter
。我不想使用object,有没有更好的方法,我可以在一个新的抽象类中使用泛型方法并重写它?实际上我在考虑第二个解决方案,非泛型基类
List<Base> values = GetValues();
foreach (Base value in values)
{
switch (value.DataType)
{
case DataType.MyString:
MyString myString = value as MyString;
...
case DataType.MyInt:
MyInt myInt = value as MyInt;
...
}
}
foreach (Base value in values)
{
if (value is MyString)
{
MyString myString = value as MyString;
...
}
else if (value is MyInt)
{
MyInt myInt = value as MyInt;
...
}
}