我有这个C#代码
public interface IDinnerRepository : IRepository<Dinner>
{
IQueryable<Dinner> FindByLocation(float latitude, float longitude);
IQueryable<Dinner> FindUpcomingDinners();
IQueryable<Dinner> FindDinnersByText(string q);
void DeleteRsvp(RSVP rsvp);
}
和
public interface IRepository<T>
{
IQueryable<T> All { get; }
IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties);
T Find(int id);
void InsertOrUpdate(T dinner);
void Delete(int id);
void SubmitChanges();
}
我想翻译成F#。如何创建泛型界面? F#接口的MSDN示例实际上没有等价物。据我所知。
答案 0 :(得分:5)
实际上有两种方法可以定义通用接口,但几乎所有F#代码都使用您在现有答案中提到的样式。另一个选项仅用于某些标准F#类型,例如'T option
和'T list
:
type IRepository<'T> = // The standard way of doing things
type 'T IRepository = // Used rarely for some standard F# types
至于您的示例界面中出现的其他成员类型,其中一些实际上有点有趣,所以这里有一个更完整的翻译(仅供将来参考!)
// We inherit from this type later, so I moved it to an earlier location in the file
type IRepository<'T> =
// Read-only properties are easier to define in F#
abstract All : IQueryable<'T>
// Annotating parameter with the 'params' attribute and also specifying param name
abstract AllIncluding
: [<ParamArray>] includeProperties:Expression<Func<'T, obj>>[] -> IQueryable<'T>
type IDinnerRepository =
// Inherit from another interface
inherit IRepository<Dinner>
// And add a bunch of other members (here I did not specify parameter names)
abstract FindUpcomingDinners : unit -> IQueryable<Dinner>
abstract FindDinnersByText : string -> IQueryable<Dinner>
答案 1 :(得分:2)
好的,我应该首先使用泛型“F#接口”。
type public IRepository<'T> =
会工作......