【问题标题】:How can I assign a new action to an existing method?如何将新操作分配给现有方法?
【发布时间】:2015-04-02 11:14:44
【问题描述】:

我在 C# 中创建了一个使用“Action”方法的类。

public void Action()
{

}

该方法是空的,因为当创建该类的新实例时,用户应该能够定义该方法的作用。一个用户可能需要该方法来写入控制台,另一个用户可能希望它为变量赋值等。我有什么办法可以改变该方法在其原始定义之外可以做什么,沿着以下:

//Using the instance "MyClass1", I have assigned a new action to it (Writing to the console)
//Now the method will write to the console when it is called
MyClass1.Action() = (Console.WriteLine("Action"));

【问题讨论】:

  • 可能想研究委托和匿名方法。但这似乎是一种相当不稳定的代码执行方式。你考虑过继承吗?

标签: c# .net class methods instance


【解决方案1】:

通过使其抽象,继承类并覆盖方法。

public class FooBase
{
    public abstract void Bar();
}

public class Foo1 : FooBase
{
    public override void Bar()
    {
        // Do something
    }
}

public class Foo2 : FooBase
{
    public override void Bar()
    {
        // Do something else
    }
}

【讨论】:

    【解决方案2】:

    我有什么办法可以改变该方法在 原来的定义

    不是通过“命名方法”以及您在示例中使用它们的方式。如果您希望您的类能够调用用户定义的执行单元,您需要查看继承层次结构(如@CodeCaster 通过虚拟方法的答案中指定并覆盖它们),或者查看delegates

    您可以使用Action 委托:

    public Action Action { get; set; }
    

    像这样使用它:

    var class = new Class();
    class.Action = () => { /*Code*/ }
    

    而且,当你想调用它时:

    if (class.Action != null)
    {
       class.Action();
    }
    

    【讨论】:

    • 领先我 2 秒 :)
    • 请记住,当您调用 Action() 时,它可能为空。而且您不能使用“类”作为标识符。
    • @Dennis_E 添加了无效性检查:)
    • 我认为这个答案缺乏一些解释。这个问题听起来很像 OP 的印象,常规方法是可变实体,其实现可以在运行时替换。
    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 2018-04-16
    • 2020-09-20
    • 1970-01-01
    • 2016-02-06
    相关资源
    最近更新 更多