C#覆盖实例方法

tst*_*rzl 5 .net c#

所以基本上我有一个对象,它接受实例并将它们添加到列表中.每个实例都使用虚拟方法,创建实例后我需要覆盖这些方法.我将如何重写实例的方法?

Jus*_*ner 15

你不能.您只能在定义类时覆盖方法.

最好的选择是使用适当的Func委托作为占位符,并允许调用者以这种方式提供实现:

public class SomeClass
{
    public Func<string> Method { get; set; }

    public void PrintSomething()
    {
        if(Method != null) Console.WriteLine(Method());
    }
}

// Elsewhere in your application

var instance = new SomeClass();
instance.Method = () => "Hello World!";
instance.PrintSomething(); // Prints "Hello World!"
Run Code Online (Sandbox Code Playgroud)