【问题标题】:How to call method().method() in C# [duplicate]如何在 C# 中调用 method().method() [重复]
【发布时间】:2013-01-07 09:24:30
【问题描述】:

可能重复:
Method-Chaining in C#
creating API that is fluent

我该如何进行下面的编码?

Class1 objClass1 = new Class1().Add(1).Add(2).Add(3)...

等等……

我如何实现Add() 方法来调用将反映在同一对象上的无限时间?

【问题讨论】:

  • 使用return this;,你的方法必须有返回类型Class1

标签: c#


【解决方案1】:

从逻辑上讲,如果您想在调用后使用同一个对象,则必须返回该对象,该对象在方法中用 this 引用。

class Class1
{
    public Class1 Add(int num)
    {
        //TODO
        return this;
    }
}

这是一个方法链的例子。

【讨论】:

  • 这种设计风格的另一个名称是流畅的界面
【解决方案2】:

它被称为chainable methods

方法链接,也称为命名参数习语,是一种常见的 在面向对象中调用多个方法调用的技术 编程语言。每个方法都返回一个对象(可能是 当前对象本身),允许将调用链接在一起 单个语句。

基本上,您的方法应该返回对象的当前实例。

public YourClass Add()
{
    return this;
}

为了清楚地理解方法链,这里是从 Java 转换而来的代码,包含在 wikipedia 页面中。设置器返回“this”(当前的Person 对象)。

using System;

namespace ProgramConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Person person = new Person();
            // Output: Hello, my name is Soner and I am 24 years old.
            person.setName("Soner").setAge(24).introduce();
        }
    }

    class Person
    {
        private String name;
        private int age;

        public Person setName(String name)
        {
            this.name = name;
            return this;
        }

        public Person setAge(int age)
        {
            this.age = age;
            return this;
        }

        public void introduce() {
                Console.WriteLine("Hello, my name is " + name + " and I am " + age + " years old.");
        }
    }
}

【讨论】:

  • 对像我这样的新手来说很好的解释。
【解决方案3】:

你必须返回对象本身来链接这样的方法调用

public Class1 Add(Object Whatever)
{
    // Do code here
    return this;
}

【讨论】:

    猜你喜欢
    • 2011-02-14
    • 1970-01-01
    • 2016-05-11
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    相关资源
    最近更新 更多