我从C#开始使用VB.Net时,有一个代码翻译站点。最好在F#中使用
我写了这个C#代码
public interface IData : INotifyPropertyChanged
{
Guid ID { get; set; }
}
public interface IVertex : INotifyPropertyChanged
{
}
public abstract class Vertex<IData>
{
public IData Properties { get; set; }
public Vertex() { }
public Vertex(IData Properties)
{
this.Properties = Properties ;
}
public string Tipo { get { return typeof(IData).Name; } }
}
public class Data_Person : IData
{
public event PropertyChangedEventHandler PropertyChanged;
public Guid ID { get; set; } = Guid.NewGuid();
public decimal Balance { get; set; }
public string Name { get; set; }
}
public class Person : Vertex<Data_Person>, IVertex
{
public Person()
{
this.Properties = new Data_Person();
}
public Person(Data_Person Properties) : base(Properties)
{ }
public event PropertyChangedEventHandler PropertyChanged;
}
public class EdgeLink<ISourceVertex, IEdgeData, ITargetVertex>
{
public EdgeLink()
{ }
public EdgeLink(ISourceVertex In, IEdgeData Edge, ITargetVertex Out)
{
this.In = In;
this.Properties = Edge;
this.Out = Out;
}
public ISourceVertex In { get; set; }
public IEdgeData Properties { get; set; }
public ITargetVertex Out { get; set; }
//public LoadStatus LoadStatus { get; set; } = LoadStatus.Uknown;
}
我正在尝试做同样的事情,但是在F#中。
如何将其“翻译”为F#?
我尝试翻译,但很混乱,到目前为止,我已经
type IData =
inherit INotifyPropertyChanged
abstract member ID: Guid with get, set
type IEdgeData =
inherit IData
type IVertex =
inherit INotifyPropertyChanged
type ISourceVertex =
inherit IVertex
type ITargetVertex =
interface
inherit IVertex
end
答案 0 :(得分:4)
由于注释表明您在处理事件和泛型类型时遇到问题,因此,请按照以下方法进行转换,具体来说:
open System
open System.ComponentModel
type IData =
inherit INotifyPropertyChanged
abstract member ID: Guid
type IVertex = inherit INotifyPropertyChanged
[<AbstractClass>]
type Vertex<'data when 'data :> IData> (properties: 'data) =
member __.Properties = properties
member __.Tipo = typeof<'data>.Name
type DataPerson (id, balance, name) =
let propertyChanged = Event<_,_>()
member __.ID = id
member __.Balance = balance
member __.Name = name
interface IData with
member __.ID = id
[<CLIEvent>]
member __.PropertyChanged = propertyChanged.Publish
您只需要将通用类型变量'data
约束为IData
类的Vertex
,并将F#Event<_,_>
约束为{{1 }}事件。
注意,我在这里省略了属性的设置器。如果确实需要它们,可以轻松地将它们重新添加回去。
编辑
添加人员类别:
PropertyChanged
编辑2
在构造函数中添加可选参数(这次我也使type Person (person) =
inherit Vertex<DataPerson>(person)
let propertyChanged = Event<_,_>()
interface IVertex with
[<CLIEvent>]
member this.PropertyChanged = propertyChanged.Publish
属性变得可变,因为如果您可以使用未初始化的类来实例化它,则保持不变是没有多大意义的)。在纯F#解决方案中,我可能不会这样做,但这是原始C#代码的更直接表示:
Vertex.Properties