gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:04:48 25 4
gpt4 key购买 nike

是否可以在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com