英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论