一个对象表达式可以引用自身吗?

huangapple go评论43阅读模式
英文:

Can an object expression refer to itself?

问题

我正在探讨将我们的C#代码库转换为F#。这个代码库使用一个外部库,该库提供了一个接口;其中的一个方法允许库创建我们类的新实例:

public class Worker : IWorker
{
    public IWorker CreateNewInstance()
    {
        return new Worker();
    }
}

鉴于这些类的数量,我想利用对象表达式。对象表达式是否可以以这种方式引用自身?

英文:

I'm exploring converting our C# codebase to F#. This codebase uses an external library that provides an interface; one of the methods allows the library to create new instances of our class:

public class Worker : IWorker
{
    public IWorker CreateNewInstance()
    {
        return new Worker();
    }
}

Given the number of these classes, I'd like to take advantage of object expressions. Is there a way an object expression can refer to itself in this way?

答案1

得分: 2

以下是翻译好的部分:

我不确定是否会在不了解更多有关您的用例的情况下建议这样做但类似这样的代码应该可以工作

```fsharp
let rec makeWorker () =
    {
        new IWorker with
            member _.CreateNewInstance() = makeWorker ()
    }

let worker1 = makeWorker ()
let worker2 = worker1.CreateNewInstance()

希望这对您有所帮助。如果您有任何其他问题,请随时提问。

英文:

I'm not sure I would recommend this without knowing more about your use case, but something like this should work:

let rec makeWorker () =
    {
        new IWorker with
            member _.CreateNewInstance() = makeWorker ()
    }

let worker1 = makeWorker ()
let worker2 = worker1.CreateNewInstance()

huangapple
  • 本文由 发表于 2023年2月14日 02:54:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定