假设我有这门课
public class Foo<T>
{
public List<T> FooList { get; set;}
}
这个类被另一个类使用,例如:
public class Bar
{
public List<Foo> Foos { get; set; } // THIS DOESNT COMPILE
}
上面的解决方案不起作用,因为它说我的通用类型 Foo
需要 1 个类型参数。
在我的真实场景中,我认为将泛型传播到 Bar
没有多大意义。类,例如:
public class Bar<T>
{
public List<Foo<T>> Foos { get; set; } // Not the solution I want
}
所以我想知道:如果有的话,哪个是最好的解决方案?我真的需要制作我的 Bar
吗?类通用?在 Java 中,如果我没记错的话,我可以做类似 List<Foo<?>> Foos
的事情。它会起作用...
编辑
所以,按照要求,我给出了具体的例子。
我正在为 Highcharts 做一些 DTO 类(class).
在许多其他对象中,Highcharts 具有 series
目的。这series
对象有 data
属性几乎可以是任何东西:数字列表、数字对列表等。
所以我的通用类是系列:
public class SeriesDto<T>
{
public List<T> Data { get; set; }
// Other options ...
}
它会被 HighchartsDto
使用类:
public class HighchartsDto {
// Lot of things..
// ...
public List<SeriesDto> Series { get; set; } // doesn't compile
}
制作HighchartsDto
没有意义通用,因为同一个图表可以有不同类型的系列。
最佳答案
你可以添加一个接口(interface):
public interface IFoo
{
}
public class Foo<T> : IFoo
{
public List<T> FooList { get; set; }
}
public class Bar
{
public List<IFoo> Foos { get; set; }
}
关于c# - 具有通用属性的类必须是通用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50093332/