简体   繁体   English

F#属性与C#属性

[英]F# properties vs. C# properties

In developing an F# application, I have a type that comprises a property of type Lazy<'T> . 在开发F#应用程序时,我具有一个包含Lazy<'T>类型的属性的类型。

Apparently, one interesting side effect (pardon the pun) of the way that F# handles the syntactical sugar of properties (as opposed to the C# way) is that the getter and setter of a property may return/accept different types. 显然,F#处理属性的语法糖(与C#方法相反)的方式的一个有趣的副作用(对双关语)是属性的获取器和设置器可能返回/接受不同的类型。 (At least, Visual Studio is not complaining as I write code that takes advantage of this observation.) (至少,在我编写利用此观察结果的代码时,Visual Studio并没有抱怨。)

For example, it is advantageous for me to do this: 例如,这样做对我来说是有利的:

let lazyValue = lazy 0

member this.Value
    with get () =
        lazyValue.Value
    and set _lazyVal =
        lazyValue <- _lazyVal

... such that Value returns an int , but accepts only a Lazy<int> . ...这样Value会返回一个int ,但仅接受 Lazy<int>

What I am wondering about are the theoretical, idiomatic, and practical objections to doing things this way. 我想知道的是以这种方式做事的理论,惯用和实践上的反对。 Is this something at which an F# snob would turn up his nose? 这是F#势利小人抬起鼻子来的东西吗? Is there some functional programming rule of thumb that this (object-oriented implementation) clearly violates? 是否有一些明显违反此功能性编程规则(面向对象的实现)? Is this an approach that has been demonstrated to cause problems in large-scale applications? 已经证明这种方法会在大规模应用中引起问题吗? If so, why/how? 如果是这样,为什么/如何?

Perhaps it is a bug that "Visual Studio is not complaining as [you] write code that takes advantage of this observation". 也许这是“ Visual Studio在抱怨您(您)编写利用此观察结果的代码时没有抱怨”的错误。 See Using F# Option Type in C# 请参见在C#中使用F#选项类型

A comment in the answer to the linked question notes: 链接的问题注释的答案中的注释:

From section 8.13.1 of the spec: If a property member has both a getter and a setter, and neither is an indexer, then the signatures of both getter and setter must imply the same property type 根据规范的第8.13.1节:如果属性成员同时具有getter和setter,但都不是索引器,则getter和setter的签名必须暗示相同的属性类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM