简体   繁体   中英

Returning Subclass instead of superclass F#

In C# we can do this:

public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath)
{
    var animalCell = (AnimalCell)collectionView.DequeueReusableCell (animalCellId, indexPath);

    var animal = animals [indexPath.Row];

    animalCell.Image = animal.Image;

    return animalCell;
}

where AnimalCell is a subclass of UICollectionViewCell .

In F# I have defined my AnimalCell like this:

[<Register ("AnimalCell")>]
type AnimalCell (handle: IntPtr) = 
    inherit UICollectionViewCell (handle)

now I am implementing the same function:

override x.GetCell(collectionView : UICollectionView, indexPath : NSIndexPath) =
    let animalCell = (collectionView.DequeueReusableCell(new NSString("ChatCell"),indexPath)) :?> AnimalCell

    let animal = animals.[indexPath.Row]

    animalCell 

This produces an error: Error FS0001: This expression was expected to have type 'UICollectionViewCell' but here has type 'AnimalCell' (FS0001)

I can fix this by doing:

animalCell :> UICollectionViewCell

but why is this necessary?

It's necessary because unlike C#, F# does not automatic conversions (except in some specific situations ).

So there's less magic and more explicit conversions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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