Generics and inheritance

G

Guest

Sorry if this is the wrong group, but I cna think not of where else to post.

I have an inheritance hierarchy in place as follows ...

PersonVisitor<T> <-- AlphabeticVisitor<T> <-- FamilyNameVisitor<T>

public interface IPerson
{
string GivenName { get; set; }
string FamilyName { get; set; }
IPerson Clone();
void Visit(PersonVisitor<IPerson> visitor);
}

public abstract class PersonVisitor<T> where T : IPerson
{
virtual public void Visit(T c) { }
}

public abstract class AlphabeticVisitor<T> : PersonVisitor<T> where T :
IPerson
{
// class code omited
}

public class FamilyNameVisitor<T> : AlphabeticVisitor<T> where T : IPerson
{
override public void Visit(T c)
{
}
}

Firstly, I would expect that I could pass an object of type
FamilyNameVisitor<T> as follows

Customer c = PeopleFactory.CreateNewCustomer("Marcus", "Barnard");
Assert.IsNotNull(c, "Failed to instantiate the Customer object");
FamilyNameVisitor<Customer> v = new FamilyNameVisitor<Customer>();
c.Visit(v);

However, I am told that this is not possible because an object of type
FamilyNameVisitor<Customer> cannot be converted to type
PersonVisitor<IPerson> (even though FamilyNameVisitor<Customer> is a
sub-class of PersonVisitor<IPerson>, AND Customer is a sub-class of IPerson)

So, I then put the following implicit conversion into the FamilyNameVisitor
class definition

public static implicit operator
PersonVisitor<IPerson>(FamilyNameVisitor<T> v)
{
return (v as PersonVisitor<IPerson>);
}

but this conversion always returns null :blush:(

Can somebody please help?

Thanks in advance
 
M

Mattias Sjögren

However, I am told that this is not possible because an object of type
FamilyNameVisitor<Customer> cannot be converted to type
PersonVisitor<IPerson> (even though FamilyNameVisitor<Customer> is a
sub-class of PersonVisitor<IPerson>, AND Customer is a sub-class of IPerson)

FamilyNameVisitor<Customer> is *not* a subclass of
PersonVisitor<IPerson>. In your case I think the easiest solution is
to make the Visit method generic as well

void Visit<T>(PersonVisitor<T> visitor) where T : IPerson


Mattias
 

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

Top