Does C# have an equivalent to Scala's structural typing?

后端 未结 4 480
小鲜肉
小鲜肉 2020-12-20 11:30

In Scala, I can define structural types as follows:

type Pressable = { def press(): Unit }

This means that I can define a function or method whi

4条回答
  •  借酒劲吻你
    2020-12-20 12:09

    As others noted, this is not really available in .NET (as this is more a matter of the runtime than a language). However, .NET 4.0 supports similar thing for imported COM interfaces and I believe this could be used for implementing structural typing for .NET. See this blog post:

    • Faking COM to fool the C# compiler

    I didn't try playing with this myself yet, but I think it might enable compiler authors to write languages with structural typing for .NET. (The idea is that you (or a compiler) would define an interface behind the scene, but it would work, because the interfaces would be treated as equivalent thanks to the COM equivalence feature).

    Also, C# 4.0 supports the dynamic keyword which, I think, could be interpreted as a structural typing (with no static type checking). The keyword allows you to call methods on any object without knowning (at compile-time) whether the object will have the required methods. This is essentially the same thing as the "Duck typing" project mentioned by Igor (but that's, of course, not a proper structural typing).

提交回复
热议问题