Java to C#: Extends in Generic

前端 未结 3 2007
粉色の甜心
粉色の甜心 2021-01-20 22:07

I am trying to convert this Java (Android) code to c# (MonoDroid) but I don\'t understand the

public class Ball         


        
3条回答
  •  天涯浪人
    2021-01-20 22:25

    It's adding a constraint to the type parameter. It's analogous to the where clause in C#.

    In Java, you have:

    public class BalloonOverlayView extends FrameLayout
    

    Where Item is a type parameter that must subclass or implement type OverlayItem. In C# this would be written as:

    public class BalloonOverlayView : FrameLayout where Item : OverlayItem
    

    You can see how the constraint is moved to the end, but otherwise analogous. It is very much common practice in C# to name type parameters prefixed with a T, so I would recommend the name TItem like so:

    public class BalloonOverlayView : FrameLayout where TItem : OverlayItem
    

    This helps make clear the pretty important distinction between type parameters and ordinary types.

    For a discussion on when you'd want to use type constraints like this, I go into this at length in a previous answer.

提交回复
热议问题