C# 如何向FormattedString添加新方法?

C# 如何向FormattedString添加新方法?,c#,C#,在我的C#代码中,我多次使用这种构造: FormattedString s = new FormattedString(); s.Spans.Add(new Span { Text = "On the ", ForegroundColor = Color.FromHex("555555") }); s.Spans.Add(new Span { Text = "settings", ForegroundColor = Color.Blue }); 我想将其简化为: FormattedString

在我的C#代码中,我多次使用这种构造:

FormattedString s = new FormattedString();
s.Spans.Add(new Span { Text = "On the ", ForegroundColor = Color.FromHex("555555") });
s.Spans.Add(new Span { Text = "settings", ForegroundColor = Color.Blue });
我想将其简化为:

FormattedString s = new FormattedString();
s.Spans.AddGray("On the ");
s.Spans.AddBlue("settings");
甚至更好

s.AddGray("On the ");
s.AddBlue("settings");
有没有一种方法可以通过某种方式扩展格式化字符串的功能来实现这一点?

是的,您可以使用

您需要一些:

公共逻辑被移动到另一个允许指定颜色的扩展方法:

public static void Add(this FormattedString formattedString, string text, Color color)
    => formattedString.Spans.Add(new Span { Text = text, ForegroundColor = color });
然后可以添加彩色跨距:

s.AddGray("On the ");
s.AddBlue("settings");
s.Add("imprtant", Color.Red);  

注意,我会使方法的名称更具描述性-
AddGraySpan
AddBlueSpan
AddSpan
。我还将从每个扩展方法返回原始的
FormattedString
实例。这将允许您使用fluent API:

var s = new FormattedString().AddGraySpan("On the ").AddBlueSpan("settings");
实施示例:

public static FormattedString AddSpan(this FormattedString formattedString,
   string text, Color color)
{
    formattedString.Spans.Add(new Span { Text = text, ForegroundColor = color });
    return formattedString;
}      

如果您想要扩展方法,请阅读扩展方法:如果您能填写//TODO,将不胜感激:-)非常感谢,但是,在我需要将其添加到FormattedString的Spans部分时,前两个代码段中该如何工作?@Alan2这就是第三个方法中发生的情况您上次的更新看起来确实非常好。如果您不介意的话,可以举一个AddGraySpan或AddBlueSpan编码的例子。@Alan2不,它们都将适当的颜色传递给第三个method@Alan2是的,对不起。粘贴副本时缺少返回类型
var s = new FormattedString().AddGraySpan("On the ").AddBlueSpan("settings");
public static FormattedString AddSpan(this FormattedString formattedString,
   string text, Color color)
{
    formattedString.Spans.Add(new Span { Text = text, ForegroundColor = color });
    return formattedString;
}