gpt4 book ai didi

c# - 如何实现方法链?

转载 作者:太空狗 更新时间:2023-10-29 22:15:15 25 4
gpt4 key购买 nike

在 C# 中,如何实现在自定义类中链接方法的能力,以便可以编写如下内容:

myclass.DoSomething().DosomethingElse(x); 

等...

谢谢!

最佳答案

链接是从现有实例生成新实例的一个很好的解决方案:

public class MyInt
{
private readonly int value;

public MyInt(int value) {
this.value = value;
}
public MyInt Add(int x) {
return new MyInt(this.value + x);
}
public MyInt Subtract(int x) {
return new MyInt(this.value - x);
}
}

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7);

您也可以使用此模式修改现有实例,但通常不推荐这样做:

public class MyInt
{
private int value;

public MyInt(int value) {
this.value = value;
}
public MyInt Add(int x) {
this.value += x;
return this;
}
public MyInt Subtract(int x) {
this.value -= x;
return this;
}
}

用法:

MyInt x = new MyInt(10).Add(5).Subtract(7);

关于c# - 如何实现方法链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2055667/

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