简体   繁体   中英

c# Method override. How to call it correctly

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?

可以用virtual关键字标记基类中的方法,然后用override关键字实现子类中的方法

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;
    }
}

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
     }
   }

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