Covariance question

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi. I want the parameter type of a function to be the same type of the class.
One solution would be:
class Animal<TAnimal> where TAniman : Animal
{
public virtual void DoSomethingToTheAnimal(TAnimal animal)
{
////
}
}

class Dog : Animal<TAniman> where TAnimal : Dog
{
}


But I prefer not to require the user to include a statement like

where TAnimal : Dog

every time a class is inherited. Is there a better way to do this?

Thanks
Matt Brown
 
I'm not sure if your question is asking about generics or inheritance.
Hi. I want the parameter type of a function to be the same type of the class.

You want the parameter type of a method to be the same type as what
class, exactly? The descendant class? The generic type parameter's
class?
One solution would be:
class Animal<TAnimal> where TAniman : Animal
{
public virtual void DoSomethingToTheAnimal(TAnimal animal)
{
////
}
}

class Dog : Animal<TAniman> where TAnimal : Dog
{
}

I can't make out what you're trying to show. Are you missing definitions
for Animal and Dog? Is this second definition of Dog meant to be generic
not Dog)? Is it about the DoSomethingToTheAnimal() being said:
But I prefer not to require the user to include a statement like

where TAnimal : Dog

every time a class is inherited. Is there a better way to do this?

I have no idea what you're trying to do.

-- Barry
 
"PDHB" <[email protected]> a écrit dans le message de (e-mail address removed)...

| Hi. I want the parameter type of a function to be the same type of the
class.
| One solution would be:
| class Animal<TAnimal> where TAniman : Animal
| {
| public virtual void DoSomethingToTheAnimal(TAnimal animal)
| {
| ////
| }
| }
|
| class Dog : Animal<TAniman> where TAnimal : Dog
| {
| }

class Animal<TAnimal> where TAnimal : Animal
{
public virtual void DoSomethingToTheAnimal(TAnimal animal)
{
////
}
}

class Dog : Animal<Dog>
{
}

Joanna
 
"Joanna Carter [TeamB]" <[email protected]> a écrit dans le message de
%23AC%23%23L%[email protected]...

Sorry, I answered before checking this with the compiler :-)

| class Animal<TAnimal> where TAnimal : Animal

This line won't compile unless you also declare a non-generic Animal class.

The concept of an Animal that "works with" an Animal seems somewhet wrong.

If you intend to derive Dog from Animal, then you would not need to use a
generic base type.

I think you might need to do something like this :

class Animal
{
}

class Animal<animalT> : Animal where animalT : Animal
{
public virtual void DoSomethingToTheAnimal(animalT animal)
{
////
}
}

class Dog : Animal<Dog>
{
}

But it still doesn't seem like a good design to me.

Joanna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top