具有泛型参数的普通C#类不会因无明显原因而编译 [英] Trivial C# class with a generic parameter wouldn't compile for no apparent reason

查看:115
本文介绍了具有泛型参数的普通C#类不会因无明显原因而编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个通用函数,它可以处理 Top Bottom Right Rect 只读属性 - 我在第三方库中有很多这样的类。



我写道:

 内部类MyTemplate< WhatType> {
internal static void Work(WhatType what)
{
int left = what.Left;
}
};

我希望它能够工作 - C ++中的等效代码可以正常工作。然而,C#对象:


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

我没有得到它 - 为什么它会在我调用它之前尝试实例化模板?当然,键入 WhatType 还不知道,所以没有找到属性。



我做错了什么我该如何解决这个问题?

解决方案

C#泛型与C ++模板看起来很相似,但实际上完全不同。为了能够调用 Left / code>在类型为 WhatType 的对象上,必须指定 WhatType 实现接口或继承从使用通用约束定义 Left 的类。例如:

 接口IHasPosition 
{
int Left {get; }
int Top {get; }
}

内部类MyTemplate< WhatType> WhereType:IHasPosition
{
internal static void Work(WhatType what)
{
int left = what.Left;
}
};


I want a generic function that would work with types that have Top, Bottom, Right and Rect read-only properties - I have a lot of such classes in a third-party library.

I wrote this:

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

and I expect it to work - equivalent code in C++ would work okay. However C# objects:

error CS1061: 'WhatType' does not contain a definition for 'Left' and no extension method 'Left' accepting a first argument of type 'WhatType' could be found (are you missing a using directive or an assembly reference?)

I don't get it - why would it try to instantiate the template before I even call it? Of course, type WhatType is not yet known and so no properties can be found.

What am I doing wrong and how do I fix that?

解决方案

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<WhatType> where WhatType : IHasPosition
{
    internal static void Work( WhatType what )
    {
        int left = what.Left;
    }
};

这篇关于具有泛型参数的普通C#类不会因无明显原因而编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆