1

我想为“hede”方法定义“Hayt”类约束。

有没有办法定义约束,比如

Hayt<?> or Hayt<extends Huyt>

这是测试代码

class Program
    {
        static void Main(string[] args)
        {
            Hayt<Huyt> asd1 = new Hayt<Huyt>();
            Hayt<Huyt2> asd2 = new Hayt<Huyt2>();

            //there arent any problem here
            hede<Hayt<Huyt>>(asd1);

            //runtime error
            hede<Hayt<Huyt2>>(asd2);
        }

        static T hede<T>(T vede)
            where T : Hayt<Huyt>
        {
            return vede;
        }
    }

    public class Hayt<T>
        where T : Huyt

    {

    }

    public class Huyt
    {

    }

    public class Huyt2 : Huyt
    {

    }

它可能像这样

static void Main(string[] args)
{
    Hayt<Huyt> asd1 = new Hayt<Huyt>();
    Hayt<Huyt2> asd2 = new Hayt<Huyt2>();

    hede<Hayt<Huyt>, Huyt>(asd1);

    hede<Hayt<Huyt2>, Huyt2>(asd2);
}

static T hede<T, B>(T vede)
    where B : Huyt
    where T : Hayt<B>
{
    return vede;
}

但我认为可能有更好的解决方案

对不起,我的英语不好。

4

1 回答 1

2

这就是你要做的。没有更平滑的方法。

但请注意,C# 4.0 在混合中添加了协变和逆变。参见例如

于 2012-09-02T19:11:19.893 回答