为什么我不能投派生泛型类型立足非通用型(通过约束)? [英] Why I cannot cast derived generic type to base non-generic type (through a constrain)?

查看:138
本文介绍了为什么我不能投派生泛型类型立足非通用型(通过约束)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于这种虚构的例子:

class NonGeneric
{
}

class Generic<T> : NonGeneric
    where T : NonGeneric
{
    T DoSomething()
    {
        return this; // **
    }
}

我希望它编译:通用&LT; T&GT;从非泛型导出牛逼必须是一个派生类,它满足它的约束。

I'd expect it compiles: Generic<T> derives from NonGeneric and T must be a derived class so it satisfies its constrain.

我应该能够做到这一点:

I should be able to do this:

NonGeneric obj = new Generic<NonGeneric>();

那么就应该有这个指令没有问题:

Then there should be no problem in this instruction:

return this;

或者至少是这样的:

Or at least this:

return (T)this;

不幸的是它不工作,上面的例子中并没有错误编译:

Unfortunately it doesn't work and above example doesn't compile with error:

无法将类型非泛型&LT; T&GT; 来' T

我做错了什么,我看不到它,或者它只是不允许的?为什么这样?

I'm doing something wrong, and I can't see it, or it's just not allowed? Why this?

我会避免,如果可能的话,像一个什么解决办法我描述在这个岗位(反射,动态编译的方法等等)。我会避免动态对象太(设计决定,我不能改变的)。

I would avoid, if possible, any workaround like the one I describe in this post (Reflection, dynamic compiled methods and so on). I would avoid dynamic objects too (design decision, I can't change that).

推荐答案

您是否尝试过这个?

T DoSomething()
{
    return this as T;
}

不隐式一样的 T 因此,有必要明确地将它转换为上述例。

this is not implicitly the same as T so there is a need to cast it explicitly as in the above example.

这篇关于为什么我不能投派生泛型类型立足非通用型(通过约束)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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