How does C# "this" keyword work to qualify argument in static method? [duplicate]

StackOverflow https://stackoverflow.com/questions/23458509

  •  15-07-2023
  •  | 
  •  

سؤال

I am having problem understanding the argument this flowDocument doc in the following method:

public static FormattedText GetFormattedText(this FlowDocument doc)
{
    if (doc == null)
    {
        throw new ArgumentNullException("doc");
    }
    ...
}

The caller does not specify an argument when calling the above method:

myRichTextBox.TextChanged +=
    new TextChangedEventHandler((o, e) => myRichTextBox.Width = 
        myRichTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 20);

I am positive that the method does not create doc itself. I have not seen this used in this manner before.

هل كانت مفيدة؟

المحلول

GetFormattedText() is not a normal method, but an extension method.

You can call it like this:

 document.GetFormattedText()

or this:

 ClassName.GetFormattedText(document)

نصائح أخرى

This is the syntax for an extension method, the parameter is the FlowDocument object that the method is called on:

myRichTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 20);
                   ^           
                   |
-------------------|
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top