加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#方法的Exchange实现

发布时间:2020-12-15 23:29:52 所属栏目:百科 来源:网络整理
导读:是否有可能在C#中交换方法的实现,比如在Objective-C中进行方法调整? 所以我可以在运行时用我自己的(或者在其上添加另一个)替换现有的实现(从外部源,例如通过dll). 我已经搜索过这个,但没有找到任何有价值的东西. 解决方法 您可以使用 delegates 让您的代码
是否有可能在C#中交换方法的实现,比如在Objective-C中进行方法调整?

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

我已经搜索过这个,但没有找到任何有价值的东西.

解决方法

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

public delegate void SampleDelegate(string input);

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

也可以在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",this.UploadStringToWeb);

你也可以使用Lambda表达式:DoSomething(“param1”,“param2”,(str)=> {//这里你需要做什么});

另一种方法是使用Strategy Design Pattern.在这种情况下,您声明接口并使用它们来表示所提供的行为.

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());

第二种方法比第一种方法稍微僵硬,但我认为这也是另一种方法来实现你想要的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读