所以基本上我有一个对象,需要实例并将它们添加到列表中。每个实例都使用虚拟方法,这是我需要的,一旦实例被创建覆盖。我怎么会去覆盖实例的方法?
So basically I have an object that takes instances and adds them to a list. Each instance uses virtual methods, which I need to override once the instance is created. How would I go about overriding methods of an instance?
您不能。您只能定义一个类时覆盖的方法。
You can't. You can only override a method when defining a class.
最好的办法是转而使用适当的 Func键
委托作为一个占位符,并允许呼叫者提供实现这种方式:
The best option is instead to use an appropriate Func
delegate as a placeholder and allow the caller to supply the implementation that way:
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!"