在F#C#对象初始化语法 [英] C# object initialization syntax in F#
问题描述
请注意:这个问题的不的一样这个问题
Please note: this question is not the same as this question.
我最近碰到我以前没有遇到一些C#语法传来:
I recently came across some C# syntax I hadn't previously encountered:
有什么办法?F#中做到这一点。
Is there any way to do this in F#?
class Two
{
public string Test { get; set; }
}
class One
{
public One()
{
TwoProperty = new Two();
}
public Two TwoProperty { get; private set; }
}
var test = new One(){ TwoProperty = { Test = "Test String" }};
(注意 TwoProperty
在初始化初始化时,二传手是私有的 - 它是设置存储在 TwoProperty
的对象上的属性,但是的不的存储的新实例两个
的属性)
(note the initialization of TwoProperty
in the initializer when the setter is private - it is setting a property on the object stored in TwoProperty
, but NOT storing a new instance of Two
in the property)
编辑:
我最近遇到了一些C#代码在这样的MonoTouch的构造函数来了:
I recently came across some C# code in a constructor in monotouch like this:
nameLabel = new UILabel {
TextColor = UIColor.White,
Layer = {
ShadowRadius = 3,
ShadowColor = UIColor.Black.CGColor,
ShadowOffset = new System.Drawing.SizeF(0,1f),
ShadowOpacity = .5f
}
};
最好的F#的翻译我能想出是这样的:
The best F# translation I could come up with was something like this:
let nameLabel = new UILabel ( TextColor = UIColor.White )
do let layer = nameLabel.Layer
layer.ShadowRadius <- 3.0f
layer.ShadowColor <- UIColor.Black.CGColor
layer.ShadowOffset <- new System.Drawing.SizeF(0.0f,1.0f)
layer.ShadowOpacity <- 0.5f
这并不可怕,但它确实有重复<$ C $更多的噪音C>层引用加上其更为迫切和更少的声明。
This isn't terrible, but it does have more noise with the repeated layer
reference plus its more imperative and less declarative.
推荐答案
难道是有意义的封装建设成一个单独的初始化函数?
Would it make sense to encapsulate the construction into a separate initializer function?
let layerInit layer radius color offset opacity =
do
layer.ShadowRadius <- radius
layer.ShadowColor <- color
layer.ShadowOffset <- offset
layer.ShadowOpacity <- opacity
layer // I do this in case you want to use this fluently or pass in new Layer()
然后用它在你的代码:
Then use that in your code:
let nameLabel = new UILabel ( TextColor = UIColor.White )
layerInit nameLabel.Layer 3.0f UIColor.Black.CGColor new System.Drawing.SizeF(0.0f,1.0f) 0.5f |> ignore
这篇关于在F#C#对象初始化语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!