c# - C# 方法的交换实现

标签 c# method-swizzling

是否可以在 C# 中交换方法的实现,例如 Objective-C 中的方法调配?

所以我可以在运行时用我自己的(或添加另一个)替换现有的实现(来自外部源,例如通过 dll)。

我搜索过这个,但没有找到任何有值(value)的东西。

最佳答案

你可以使用 delegates让您的代码指向您希望在运行时执行的任何方法。

public delegate void SampleDelegate(string input);

上面是一个函数指针,指向任何产生 void 并接受 string 作为输入的方法。您可以为其分配任何具有该签名的方法。这也可以在运行时完成。

也可以在MSDN 上找到一个简单的教程。 .

编辑,根据您的评论:

public delegate void SampleDelegate(string input);
...
//Method 1
public void InputStringToDB(string input) 
{
    //Input the string to DB
}
...

//Method 2
public void UploadStringToWeb(string input)
{
    //Upload the string to the web.
}

...
//Delegate caller
public void DoSomething(string param1, string param2, SampleDelegate uploadFunction)
{
    ...
    uploadFunction("some string");
}
...

//Method selection:  (assumes that this is in the same class as Method1 and Method2.
if(inputToDb)
    DoSomething("param1", "param2", this.InputStringToDB);
else
    DoSomething("param1", "param2", this.UploadStringToWeb);

您还可以使用 Lambda 表达式:DoSomething("param1", "param2", (str) => {//您需要在此处执行的操作 });

另一种选择是使用 Strategy Design Pattern .在这种情况下,您声明接口(interface)并使用它们来表示提供的行为。

public interface IPrintable
{
    public void Print();
}

public class PrintToConsole : IPrintable
{
    public void Print()
    {
        //Print to console
    }
}

public class PrintToPrinter : IPrintable
{
    public void Print()
    {
        //Print to printer
    }
}


public void DoSomething(IPrintable printer)
{
     ...
     printer.Print();
}

...

if(printToConsole)
    DoSomething(new PrintToConsole());
else
    DoSomething(new PrintToPrinter());

第二种方法比第一种方法稍微严格一些,但我认为这也是实现您想要的目标的另一种方法。

关于c# - C# 方法的交换实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34507043/

相关文章:

c# - 在 C# 中继承泛型的一个很好的理由

c# - "The image format is unrecognized"取决于显示器

c# - 打印机属性对话框保存的更改

c# - 使用 Entity Framework 执行后期绑定(bind)存储过程

objective-c - method swizzling 和 isa swizzling 是一回事吗?

swift - NSLocale.currentLocale 的端口方法 swizzle 从 swift 2.3 到 swift 3

Objective-C:调配方法调用的方法应该调用原始实现

c# - 如何在 C# 中可靠地确定字符的宽度?

ios - Swizzling UIImage.init(名为 :) returns nil when getting the instance method

objective-c - 在方法调配中使用 dispatch_once