如何在F#中实现C#接口?

7

我想在F#中实现以下C#接口:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Addins;

[TypeExtensionPoint]
public interface ISparqlCommand
{
    string Name { get; }
    object Run(Dictionary<string, string> NamespacesDictionary,    org.openrdf.repository.Repository repository, params object[] argsRest);
}   

这是我尝试过的,但它给了我一个错误提示:"表达式中此处或之前存在不完整的结构体构造"。
#light

module Module1

open System
open System.Collections.Generic;

type MyClass() =
    interface ISparqlCommand with
        member this.Name = 
            "Finding the path between two tops in the Graph"
        member this.Run(NamespacesDictionary, repository, argsRest) = 
            new System.Object

我做错了什么?也许是缩进出了问题?

6
也许只是漏掉了 new System.Object() 的括号? - Mark H
1
什么是C#接口?您已在C#中定义了一个CLR接口。 - John Saunders
2个回答

5

我在评论中验证了@Mark的答案。给定以下C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace org.openrdf.repository {
    public class Repository {
    }
}

namespace CSLib
{

    [System.AttributeUsage(System.AttributeTargets.Interface)]
    public class TypeExtensionPoint : System.Attribute
    {
        public TypeExtensionPoint()
        {
        }
    }


    [TypeExtensionPoint]
    public interface ISparqlCommand
    {
        string Name { get; }
        object Run(Dictionary<string, string> NamespacesDictionary, org.openrdf.repository.Repository repository, params object[] argsRest);
    }

}

以下是 F# 实现(唯一的变化是在对象构造中添加 ())可以正常工作:
#light

module Module1

open System
open System.Collections.Generic;
open CSLib

type MyClass() =
    interface ISparqlCommand with
        member this.Name = 
            "Finding the path between two tops in the Graph"
        member this.Run(NamespacesDictionary, repository, argsRest) = 
            new System.Object()

虽然你不需要再使用#light(它是默认值),但你可能想注意NamespaceDictionary参数名称的警告:"模式中通常不应使用大写变量标识符,并且可能表示拼写错误的模式名称"。此外,请注意,为了访问实现的成员(这不是你提出的问题,但从C#过来很容易混淆),你需要将MyClass强制转换为ISparqlCommand:例如,(MyClass() :> ISparqlCommand).Name


1

谢谢大家!下面的代码确实可以工作:

namespace MyNamespace

open System
open System.Collections.Generic;
open Mono.Addins

[<assembly:Addin>]
    do()
[<assembly:AddinDependency("TextEditor", "1.0")>]
    do()

[<Extension>]
type MyClass() =
    interface ISparqlCommand with
         member this.Name
             with get() = 
                 "Finding the path between two tops in a Graph"
         member this.Run(NamespacesDictionary, repository, argsRest) = 
             new System.Object()

这也是如何在 F# 中使用 Mono.Addins 的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接