[英]List of Generics T using Interface
Following these two SO questions: 遵循以下两个SO问题:
Is it possible to use a list of untyped generics in C#? 是否可以在C#中使用无类型的泛型列表?
and 和
How am I able to create A List<T> containing an open generic Interface? 如何创建包含打开的通用接口的List <T>?
public interface IValue
{
object Min { get; set; }
object Max { get; set; }
object Avg { get; set; }
}
public abstract class Value<T> : IValue
{
abstract T Min;
abstract T Max;
abstract T Avg;
object IValue.Avg { get { return Avg; } }
object IValue.Min { get { return Min; } }
object IValue.Max { get { return Max; } }
public Value(T min, T max, T avg)
{
Min = min;
Max= max;
Avg = avg;
}
}
Somewhere else in code.... 代码中的其他地方。
Value myValue = new Value<ulong>(x, y, z);
Value myValue = new Value<ushort>(x, y, z);
List<IValue> myList = new List<IValue>();
myList.add(myValue);
//Do stuff like myList[0].Min
I can't get this to work properly. 我无法使它正常工作。 I Imagine it has to do with my interface and how I'm using it. 我想像它与我的界面以及我的使用方式有关。 I want to be able to call a constructor and set the values however I need to. 我希望能够调用构造函数并设置所需的值。
I get errors like "modifier 'abstract' not valid on fields. Try a property instead" and "Cannot create an instance of the abstract class of interface Value" but I also can't do new IValue either. 我收到类似“修饰符'抽象'在字段上无效。请尝试使用属性”和“无法创建接口Value的抽象类的实例”之类的错误,但是我也不能执行新的IValue。
You can't create an object of an interface, so you can't do new IValue()
. 您无法创建接口的对象,因此无法执行new IValue()
。
You can't create an object of an abstract type, so you can't do new Value<SomeType>()
either. 您不能创建抽象类型的对象,因此也不能创建new Value<SomeType>()
。
In Value<T>
, Min
, Max
and Avg
are fields , and fields cannot be abstract. 在Value<T>
, Min
, Max
和Avg
是字段 ,并且字段不能是抽象的。 You want to make properties instead: 您想改为设置属性:
public abstract T Min { get; set; } public abstract T Max { get; set; } public abstract T Avg { get; set; }
You probably don't want to use abstract
at all. 您可能根本不想使用abstract
。 Value<T>
looks pretty complete, and given that you expect to be able to create it, there is no reason to have it as an abstract type. Value<T>
看起来很完整,并且鉴于您希望能够创建它,因此没有理由将其作为抽象类型。
Why do you use abstract at all? 为什么根本使用抽象 ? If you want to create class instances the class can't be abstract . 如果要创建类实例,则该类不能是抽象的 。
public class Value<T>: IValue {
// Better to name these fields as "min, max, ave" or "m_Min, m_Max, m_Ave"
T Min;
T Max;
T Avg;
// Do not forget about "set" accessors
object IValue.Avg {
get { return Avg; }
set { Avg = (T) value; }
}
object IValue.Min {
get { return Min; }
set { Min = (T) value; }
}
object IValue.Max {
get { return Max; }
set { Max = (T) value; }
}
public Value(T min, T max, T avg) {
Min = min;
Max = max;
Avg = avg;
}
}
...
// "Value<ulong> myValue" instead of "Value myValue "
Value<ulong> myValue = new Value<ulong>(x, y, z);
List<IValue> myList = new List<IValue>();
myList.Add(myValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.