C#泛型约束上传播 [英] C# generics contraints propagation

查看:129
本文介绍了C#泛型约束上传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这例子是真正的问题的简化,但我怎么能得到这个编译?我期望泛型约束来传播。



由于T是一个TClass和TClass是一个类,为什么心不是T A类?



 公共类MyClass的< TClass>在这里TClass:类
{
公共无效FuncA的行<钽>()其中Ta:类
{
}

公共无效FuncB<铽>( )其中TB:TClass
{
}

公共无效Func键< T>()
,其中T:TClass
{
FuncA的行< T>();
FuncB< T>();
}
}

修改



这实际工作。埃里克利珀让我觉得,谢谢。



由于T是一个TClass和TClass是TAnotherType,T实际上是TAnotherType。

 公共类MyClass的< TClass,TAnotherType>在这里TClass:TAnotherType 
{
公共无效FuncA的行<钽>()其中Ta:TClass
{
}

公共无效FuncB<铽>( )其中TB:TAnotherType
{
}

公共无效Func键< T>()
,其中T:TClass
{
FuncA的行< T>();
FuncB< T>();
}
}


解决方案

有关编制这一做;

 公共无效Func键< T>()
,其中T:类,TClass
{
&FuncA的行LT; T>();
FuncB< T>();
}

由于FUNA的输入就是一个类没有特殊的类。


This example is a simplification of the real problem, but how can I get this to compile? I would expect the generics constraints to propagate.

Since T is a TClass and TClass is a class, why isnt T a class?

public class MyClass<TClass> where TClass : class 
{
    public void FuncA<Ta>() where Ta : class
    {
    }

    public void FuncB<Tb>() where Tb : TClass
    {
    }

    public void Func<T>()
        where T : TClass
    {
        FuncA<T>();
        FuncB<T>();
    }
}

EDIT:

This actually works. Eric Lippert made me think, thanks.

Since T is a TClass and TClass is a TAnotherType, T is actually TAnotherType.

public class MyClass<TClass, TAnotherType> where TClass : TAnotherType
{
    public void FuncA<Ta>() where Ta : TClass
    {
    }

    public void FuncB<Tb>() where Tb : TAnotherType
    {
    }

    public void Func<T>()
        where T : TClass
    {
        FuncA<T>();
        FuncB<T>();
    }
}

解决方案

For compiling this do;

public void Func<T>()
    where T :class, TClass
{
    FuncA<T>();
    FuncB<T>();
}

because input of FunA is just a class not special class.

这篇关于C#泛型约束上传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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