温馨提示×

c#方法 如何实现方法链

c#
小樊
82
2024-07-14 05:21:21
栏目: 编程语言

在C#中,可以通过在方法中返回this对象来实现方法链。例如:

public class MyClass
{
    private int value;

    public MyClass SetValue(int val)
    {
        this.value = val;
        return this;
    }

    public MyClass Add(int val)
    {
        this.value += val;
        return this;
    }

    public int GetValue()
    {
        return this.value;
    }
}

class Program
{
    static void Main()
    {
        MyClass myClass = new MyClass();
        int result = myClass.SetValue(5).Add(3).GetValue();

        Console.WriteLine(result);  // Output: 8
    }
}

在上面的例子中,SetValue和Add方法都返回this对象,这样就可以在同一行代码中调用多个方法,形成方法链。

0