C#重写实例方法 [英] C# override instance method

查看:108
本文介绍了C#重写实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有一个对象,需要实例并将它们添加到列表中。每个实例都使用虚拟方法,这是我需要的,一旦实例被创建覆盖。我怎么会去覆盖实例的方法?

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!"

这篇关于C#重写实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆