假设有一个带有一个公共构造函数的类,它接受一个参数.此外,我还想设置多个公共属性.F#中的语法是什么?例如在C#中
public class SomeClass
{
public string SomeProperty { get; set; }
public SomeClass(string s)
{ }
}
//And associated usage.
var sc = new SomeClass("") { SomeProperty = "" };
Run Code Online (Sandbox Code Playgroud)
在F#中,我可以使用构造函数或属性设置器完成此操作,但不能同时使用C#.例如,以下内容无效
let sc1 = new SomeClass("", SomeProperty = "")
let sc2 = new SomeClass(s = "", SomeProperty = "")
let sc3 = new SomeClass("")(SomeProperty = "")
Run Code Online (Sandbox Code Playgroud)
看起来我错过了什么,但是什么?
<编辑:正如David指出的那样,在F#中完成所有工作,但由于某种原因,至少对我来说:),当在F#中使用的类在C#中定义时,它变得很困难.至于这样的一个例子是TopicDescription(为了补充一个例子来构建公开的东西).例如,人们可以写
let t = new TopicDescription("", IsReadOnly = true)
Run Code Online (Sandbox Code Playgroud)
并且相应的编译器错误将是Method 'set_IsReadOnly' is not accessible from this code location.
我从不用F#编程,但这对我来说似乎很好用:
type SomeClass(s : string) =
let mutable _someProperty = ""
let mutable _otherProperty = s
member this.SomeProperty with get() = _someProperty and set(value) = _someProperty <- value
member this.OtherProperty with get() = _otherProperty and set(value) = _otherProperty <- value
let s = new SomeClass("asdf", SomeProperty = "test");
printf "%s and %s" s.OtherProperty s.SomeProperty;
Run Code Online (Sandbox Code Playgroud)
那输出"asdf and test".
此外,以下代码适合我:
public class SomeClass
{
public string SomeProperty { get; set; }
public string OtherProperty { get; set; }
public SomeClass(string s)
{
this.OtherProperty = s;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在F#中:
let s = SomeClass("asdf", SomeProperty = "test")
Run Code Online (Sandbox Code Playgroud)
你遇到的问题是IsReadOnly有内部制定者.
member IsReadOnly : bool with get, internal set
Run Code Online (Sandbox Code Playgroud)
如果你想直接设置它,你将需要子类TopicDescription.
您正在查看的构造函数语法是完全可以接受的.
let test = new Microsoft.ServiceBus.Messaging.TopicDescription("", EnableBatchedOperations=true)
Run Code Online (Sandbox Code Playgroud)
编译对我来说很好.
| 归档时间: |
|
| 查看次数: |
599 次 |
| 最近记录: |