1

i want to define "Hayt" class constraint for "hede" method.

is there a way for define constraint like

Hayt<?> or Hayt<extends Huyt>

this is the test code

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
    {

    }

and its possible like this

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;
}

but i think there are probably better off solution

sorry for my bad english.

4

1 に答える 1

2

This is what you'd do. There is no smoother method.

Note though, that C# 4.0 adds co-variance and contra-variance to the mix. See e.g.

于 2012-09-02T19:11:19.893 に答える