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

后端 未结 7 820
夕颜
夕颜 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:41

    C# generics are not templates; they are provided at runtime, not by compiler magic. As such, there is no duck-typing. Two options:

    • use a where WhatType : ISomeInterface constraint, where ISomeInterface has a Left {get;}
    • use dynamic (which provides duck-typing)

    i.e.

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

    or:

    internal class MyTemplate<WhatType> {
        internal static void Work( WhatType what )
        {
            int left = ((dynamic)what).Left;
        }
    };
    
    0 讨论(0)
提交回复
热议问题