带有泛型参数的普通C#类无法编译,没有明显的原因

sha*_*oth 1 .net c# generics templates

我想一个通用的功能,将与有类型的工作Top,Bottom,RightRect只读属性-我有一个第三方库有很多这样的类.

我写了这个:

internal class MyTemplate<WhatType> {
    internal static void Work( WhatType what )
    {
        int left = what.Left;
    }
};
Run Code Online (Sandbox Code Playgroud)

我希望它能够正常工作--C++中的等效代码可以正常工作.但是C#对象:

错误CS1061:'WhatType'不包含'Left'的定义,并且没有扩展方法'Left'接受类型'WhatType'的第一个参数可以找到(你是否缺少using指令或程序集引用?)

我不明白 - 为什么它会在我调用它之前尝试实例化模板?当然,类型WhatType尚不清楚,因此无法找到属性.

我做错了什么,我该如何解决?

Mar*_*ell 8

C#泛型不是模板; 它们是在运行时提供的,而不是由编译魔术提供的 因此,没有鸭子打字.两种选择:

  • 使用where WhatType : ISomeInterface约束,其中ISomeInterface有一个Left {get;}
  • 使用dynamic(提供鸭子打字)

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

要么:

internal class MyTemplate<WhatType> {
    internal static void Work( WhatType what )
    {
        int left = ((dynamic)what).Left;
    }
};
Run Code Online (Sandbox Code Playgroud)

  • @Sharptooth否.您放弃编译时安全性以使用dynamic关键字. (2认同)