Home > database >  c# Method override. How to call it correctly
c# Method override. How to call it correctly

Time:11-06

learning c #, and trying to write a post search

in this code everything worked out for me:

using System;
using System.Collections.Generic;

namespace _3._1
{
    class Program {
        static void Main(){
            List<Message> messages = new List<Message>();

            messages.Add(new SmsMessage {text = "Hello!"});
            messages.Add(new SmsMessage {text = "What?"});
            messages.Add(new SmsMessage {text = "You?"});
            
            messages.Add(new EmailMessage {text = "Show"});
            messages.Add(new EmailMessage {text = "You!"});
            messages.Add(new EmailMessage {text = "Hello!"});


            string query = Console.ReadLine();
            int i = 0;
            foreach(Message str in messages){
                if(Message.Search(str, query)){
                    i  ;
                }
            }
            Console.WriteLine($"query: {query} | coincidences: {i}");
        }
    }
    class Message {
        public string text { get; set; }
        public static bool Search(Message message, string query){
            if(message.text.Contains(query))return true;
            return false;
        }
    }
    class SmsMessage : Message {
        public string phone;
    }
    class EmailMessage : Message {
        public string email;
        public string subject;
    }
}

but how can you override the Search method on Virtual, and reassign it in other classes so that the search works the same as before?

CodePudding user response:

static members could not be virtual and thus could not be overridden. In your case looks like you can make your Search method non static and then virtual

class Message {
    public string text { get; set; }
    public virtual bool Search(string query){
        if(this.text.Contains(query))return true;
        return false;
    }
}
class SmsMessage : Message {
    public string phone;
    public virtual bool Search(string query){
            //search code here;
    }
}

CodePudding user response:

If you want to override method, it cannot be static (static methods could not be overridden) and have to be virtual. So remove the static keyword in your search method definition and make the method virtual.

  class Message {
    public string text { get; set; }
    public virtual bool Search(Message message, string query){
        if(message.text.Contains(query))return true;
        return false;
     }
   }

  class SmsMessage : Message {
    public string phone;
    public override bool Search(Message message, string query) {
       // do something
     }
   }

CodePudding user response:

You can mark the method in the base class with the virtual keyword, then implement the method in the child classes with the override keyword

  • Related