C# 如何创建无限属性?

C# 如何创建无限属性?,c#,class,properties,C#,Class,Properties,在C语言中,字符串具有这样的无限属性 string a = ""; a.ToString().Length.ToString().ToUpper().ToLower().ToString().... 我怎么能这样创造呢 ClassName a = new ClassName(); a.text("message").title("hello").icon("user"); 谢谢,它很管用 public class Modal { public Modal()

在C语言中,字符串具有这样的无限属性

string a = "";
a.ToString().Length.ToString().ToUpper().ToLower().ToString()....
我怎么能这样创造呢

ClassName a = new ClassName();
a.text("message").title("hello").icon("user");
谢谢,它很管用

public class Modal { public Modal() { } private string Date = null; private string Text = null; private string Title = null; private string Icon = null; private string Subtitle = null; private string Confirm = "ok"; private string Cancel = "cancel"; private string Type = "warning"; public Modal text(string text) { this.Text = text; return this; } public Modal title(string title) { this.Title = title; return this; } public Modal icon(string icon) { this.Icon = icon; return this; } public Modal subtitle(string subtitle) { this.Subtitle = subtitle; return this; } public Modal confirm(string confirm) { this.Confirm = confirm; return this; } public Modal cancel(string cancel) { this.Cancel = cancel; return this; } public Modal type(string type) { this.Type = type; return this; } public void show(System.Web.UI.Page Page) { StringBuilder s = new StringBuilder(); s.Append("{'date':'" + (DateTime.UtcNow.Ticks - 621355968000000000).ToString() + "','text':'" + Text + "','title':'" + Title + "','icon':'" + Icon + "','subtitle':'" + Subtitle + "','confirm':'" + Confirm + "','cancel':'" + Cancel + "','type':'" + Type + "'}"); string _script = "showModal(" + s.ToString() + ");"; ScriptManager.RegisterStartupScript(Page, Page.GetType(), (DateTime.UtcNow.Ticks - 621355968000000000).ToString(), _script, true); } }
字符串上的每个方法都只返回一个字符串。嗯,差不多了。你的长度不正确。如果从方法返回对象,则可以实现相同的概念。在某些情况下,这可以称为流畅的语法,尽管字符串示例并不一定如此

例如,假设您的.Title方法如下:

class ClassName
{
    //...

    public ClassName Title(string title)
    {
        this.Title = title;
        return this;
    }
}
然后,无论何时调用someObj.Titlesome字符串,该方法都将返回对象本身:

var someObj = new ClassName();
someObj.Title("some title").SomeOtherOperation();

它不是无限的,它只是一个返回调用它的相同类型的方法。它可以返回自身或该类型的任何实例。当你这样做的时候,一定要注意你正在构建的界面,因为你可能会意外地创建一些非常不直观的东西。Fluent链对原始对象产生意外的副作用,或对原始对象不产生预期的效果。

它没有无限属性-它只是有各种返回字符串的方法。如果您让您的方法返回相同的类型,您也可以这样做……您的示例甚至不会编译,因为长度是int而不是字符串。这里没有属性,只有链式函数。我不认为您可以使用.ToString.Length.ToUpper,因为Length是int。。正如@JonSkeet提到的,只要每个方法返回一个字符串,您就可以继续在resultFluent接口上调用字符串方法/方法链接,这是您需要研究的,例如,也可以查看谢谢您的答案,我会尝试一下
var someObj = new ClassName();
someObj.Title("some title").SomeOtherOperation();