Trivial C# class with a generic parameter wouldn't compile for no apparent reason

后端 未结 7 825
夕颜
夕颜 2021-01-16 15:15

I want a generic function that would work with types that have Top, Bottom, Right and Rect read-only properties - I have

7条回答
  •  不知归路
    2021-01-16 15:25

    C# generics look similar to C++ templates, but they're actually quite different. C# generics are strongly typed, so you can't call a member that is not statically known.

    In order to be able to call Left on an object of type WhatType, you have to specify that WhatType implements an interface or inherits from a class that defines Left, using a generic constraint. For instance:

    interface IHasPosition
    {
        int Left { get; }
        int Top { get; }
    }
    
    internal class MyTemplate where WhatType : IHasPosition
    {
        internal static void Work( WhatType what )
        {
            int left = what.Left;
        }
    };
    

提交回复
热议问题