简体   繁体   English

在库函数中正确使用泛型 - 如何知道要给出的类型

[英]Correct use of Generics in library function - how to know what type to give

I am trying to use a library function which requires specification of a generic type in the method call. 我正在尝试使用库函数,该函数需要在方法调用中指定泛型类型。
The method should open a file and extract a number of 1-D float arrays and return them to a type of dictionary defined in the library. 该方法应该打开一个文件并提取一些一维浮点数组并将它们返回到库中定义的一种字典。

The documentation gives no examples, but does document the syntax as follows. 文档没有给出示例,但会记录如下语法。 Method I am trying to use: 我试图使用的方法:

public static NpzDictionary<T> Load<T>(byte[] bytes)
where T : class, ICloneable, IList, ICollection, IEnumerable, 
IStructuralComparable, IStructuralEquatable

http://accord-framework.net/docs/html/M_Accord_IO_NpzFormat_Load__1.htm http://accord-framework.net/docs/html/M_Accord_IO_NpzFormat_Load__1.htm

Where the NpzDictionary type is defined as: NpzDictionary类型定义为:

public class NpzDictionary<T> : IDisposable, 
    IEnumerable
where T : class, ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatab

http://accord-framework.net/docs/html/T_Accord_IO_NpzDictionary_1.htm http://accord-framework.net/docs/html/T_Accord_IO_NpzDictionary_1.htm

Here it says T is the type of arrays to be loaded. 这里它说T是要加载的数组的类型。

I am expecting float arrays so I type: 我期待浮点数组,所以我输入:

var ret = NpzFormat.Load<float>(byte_array);

However I get the following error: 但是我收到以下错误:

The type 'float' must be a reference type in order to use it as parameter 'T' in the generic type or method 'NpzFormat.Load<T>(byte[])'

What am I doing wrong? 我究竟做错了什么?

From the generic constraints you can see that the type T must be a collection type ( ICollection, IList, IEnumerable ) but it must also implement the IStructuralComparable , IStructuralEquatable and ICloneable interfaces. 从泛型约束中,您可以看到类型T必须是集合类型( ICollection, IList, IEnumerable ),但它还必须实现IStructuralComparableIStructuralEquatableICloneable接口。

As far as I know there are no types in the .Net framework that implements all these so either your library has a collection type that matches these requirements of you have to implement it yourself. 据我所知,.Net框架中没有实现所有这些类型的类型,因此要么您的库具有符合这些要求的集合类型,您必须自己实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM