简体   繁体   中英

How Can I have abstract parameters in method?

Basiclly I have a class like Individual and another class that inherits from it - IndividualForSomeAnotherWork .

I have a class called Population too and methods like Add(Individual individual) .

Can I pass the IndividualForSomeAnotherWork to Add method through Individual type? Or should I use interface or abstract class? I'm asking because I'm getting NullReferenceException all the time.

EDIT: Sorry for not answering so long. My problem was not initializing a List containing objects so I couldn't add to it. But I also wanted to know that can I pass arguments as I said earlier. Thanks for answers.

I would recommend an IIndividual type of interface. In this case, if you have:

abstract class Individual : IIndividual {

}

class IndividualForSomeOtherWork : Individual {

}

... then Population.Add(IIndividual Individual) will accept the base class Individual as well as any descendants of Individual .

Think of the interface as a contract with the Population class that any individual within it's collection will have implemented all the functions it requires of the individual.

Note that the abstract Individual is not required to implement all functions defined within the interface. If the interface requires:

interface IIndividual {
   void DoWork();
}

... then the base Individual is not knowledgeable of what specialized work an IndividualForSomeOtherWork will actually perform. So in the abstract class:

abstract void DoWork();

This function must be defined within the specialized individual descendants.

Yes, you can pass an IndividualForSomeAnotherWork to Add(Individual individual) . It should work correctly. Your error is due to something else. Try debugging it yourself, or post more details and code and we might be able to help.

In terms of what you are trying to do here, an abstract class is not fundamentally different from an interface. In both cases it's not possible to have a argument whose type exactly matches the type of the formal parameter. See DrawImage for an explicit example of this (Image is an abstract class).

The NullReferenceException you are seeing is not directly related to the parameter type being abstract.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM