0

我有以下 C# 代码:

public static T Attr<T>(this XElement x, string name)
    {
        var attr = x.Attribute(name);
        if (typeof(T) == typeof(int))
            return (T)(object)(attr == null ? 0 : int.Parse(attr.Value));

        if (typeof(T) == typeof(float))
            return (T)(object)(attr == null ? 0 : float.Parse(attr.Value));
        if (typeof(T) == typeof(String))
            return (T)(object)(attr == null ? "" : attr.Value);
        return (T)(object)null;
    }

我已经尝试了一个小时左右将其翻译成 F#,但没有取得任何成功,并且不断收到诸如“type int has no subtype ...”之类的错误消息,这让我完全糊涂了。我对动物寓言和其他运营商的探索:? :?>没有给我任何成功。

我将如何在 F# 中重写它?

4

1 回答 1

3

如果您想要相同的逻辑,您可以像 C# 一样使用 if/else,或者定义类型映射到“类型转换器”。但我可能会选择更简单的东西,比如:

type XElement with
  member this.Attr<'T>(name) = 
    match this.Attribute(XName.Get name) with
    | null -> Unchecked.defaultof<'T>
    | attr -> Convert.ChangeType(attr.Value, typeof<'T>) :?> 'T
于 2013-07-15T15:01:55.393 回答