Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
57 views
in Technique[技术] by (71.8m points)

c# - polymorphism Printing only 1 class object from the polymorphism list

How do i print only 1 class from my polymorphism list? For example you have a polymorphism list in the program.cs

List<Person> personList = new List<Person>();

static void DisplayVisitor(List<Person> pList)
        {
            foreach (Person p in pList)
            {
                if (p.Equals(Visitor))
                    Console.WriteLine(p);
            }
        }

I have Resident and Visitor classes in the Person class. I already create a couple of Residents and Visitors but how do I display only the visitors from my person list. How do i check for the Visitor object inside the list?

question from:https://stackoverflow.com/questions/65865961/c-sharp-polymorphism-printing-only-1-class-object-from-the-polymorphism-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use is operator to check p is of Visitor type or not.

The is operator checks if the runtime type of an expression result is compatible with a given type.

foreach (Person p in pList)
   {
         if (p is Visitor visitorObj)
              Console.WriteLine(visitorObj);   //I believe you have overridden `ToString()` method
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...