简体   繁体   English

c# 方法覆盖。 如何正确调用

[英]c# Method override. How to call it correctly

learning c #, and trying to write a post search学习c#,并尝试写一个帖子搜索

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 上的 Search 方法,并在其他类中重新分配它,以便搜索与以前相同?

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

static members could not be virtual and thus could not be overridden. static成员不能是virtual ,因此不能被覆盖。 In your case looks like you can make your Search method non static and then virtual在你的情况下,你可以让你的Search方法非静态,然后是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.如果你想覆盖方法,它不能是static (静态方法不能被覆盖)并且必须是虚拟的。 So remove the static keyword in your search method definition and make the method virtual .因此,删除搜索方法定义中的static关键字并使方法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
     }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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