我正在尝试在 F# 中编写一个方法,该方法根据传递到该方法的值的类型返回泛型类型的新实例。在金融服务指数中:
open System.Collections.Generic
type AttributeIndex<'a>() =
inherit SortedDictionary<'a, HashSet<int array>>()
let getNewIndexForValue (value: obj) : AttributeIndex<_> =
match value with
| :? string -> new AttributeIndex<string>()
| :? int -> new AttributeIndex<int>()
| :? float -> new AttributeIndex<float>()
| :? bool -> new AttributeIndex<bool>()
| _ -> failwith "bad value type"
let someIndexes = [
getNewIndexForValue 9;
getNewIndexForValue "testString";
getNewIndexForValue false;
getNewIndexForValue 5.67;
]
someIndexes;;
这不会编译错误
error FS0001: Type mismatch. Expecting a
AttributeIndex<string>
but given a
AttributeIndex<int>
The type 'string' does not match the type 'int'
我似乎无法弄清楚如何根据传递到函数的值参数的类型来获取具有类型参数的 Attribute 实例。我尝试了其他几种变体,但所有变体都会导致相同的类型不匹配错误。任何帮助将不胜感激。谢谢!!
UPDATE:
感谢您的回答。我现在明白了。所以现在我试图让我的“getNewIndexForValue”返回一个非通用的基本 AttributeIndex 类。我已经在 C# 中实现了它,它按照我的预期进行编译和运行:
using System;
using System.Collections.Generic;
namespace Example {
public class AttributeIndexBase : SortedDictionary<object, HashSet<int[]>> { }
public class AttributeIndex<T> : AttributeIndexBase {
public void AddToIndex(T indexValue, int[] recordKey) {
if (!this.ContainsKey(indexValue)) {
this.Add(indexValue, new HashSet<int[]> { recordKey });
}
else {
this[indexValue].Add(recordKey);
}
}
}
class Program {
static int Main(string[] args) {
var intIdx = GetIndexForValue(32);
var boolIdx = GetIndexForValue(true);
var doubleIdx = GetIndexForValue(45.67);
var someIndexes = new List<AttributeIndexBase> {
intIdx,
boolIdx,
doubleIdx
};
return 0;
}
static AttributeIndexBase GetIndexForValue(object value) {
switch (value.GetType().Name.ToLower()) {
case "int32" :
return new AttributeIndex<int>();
case "single" :
return new AttributeIndex<float>();
case "double" :
return new AttributeIndex<double>();
case "boolean" :
return new AttributeIndex<bool>();
default :
throw new ArgumentException("The type of the value param is not allowed", "value");
}
}
}
}
但是,尝试将其移植到 F# 不起作用:
module example
open System
open System.Collections.Generic
type AttributeIndexBase() =
inherit SortedDictionary<obj, HashSet<int array>>()
type AttributeIndex<'a>() =
inherit AttributeIndexBase()
let getNewIndexForValueType (value: ValueType) : AttributeIndexBase =
match value with
| :? int -> new AttributeIndex<int>()
| :? float -> new AttributeIndex<float>()
| :? bool -> new AttributeIndex<bool>()
| _ -> failwith "bad value type"
let someIndexes = [
getNewIndexForValueType 9;
getNewIndexForValueType false;
getNewIndexForValueType 5.67;
]
在我看来,这是一个非常直接的端口(除了在 F# 版本中,我将其限制为仅 ValueType),但是我收到错误:
error FS0001: This expression was expected to have type
AttributeIndexBase
but here has type
AttributeIndex<int>
F# 真的不支持像 C# 那样的子类型到父类型的强制转换吗?