2016-07-08 20 views
0

有沒有辦法使用,以延長在C#RichTextBox控件像下面的等效方法:如何使用系統的namespace我擴展RichTextBox控件只

namespace System 
{ 
    public static class StringExtensions 
    { 
     public static string PadBoth(this string str, int length) 
     { 
      int spaces = length - str.Length; 
      int padLeft = spaces/2 + str.Length; 
      return str.PadLeft(padLeft).PadRight(length); 
     } 
    } 
} 

因此,像:

namespace System.Windows.Controls 
{ 
    public static class RichTextBoxExtensions 
    { 
     public static string MyCustomMethod() 
     { 
      return "It works!"; 
     } 
    } 
} 

我知道如何通過創建一個類並繼承richtextbox對象來使用舊的方式來擴展它,但是我更喜歡做的是相反的,因爲上面向基本RichTextBox對象添加了功能,而無需創建新的自定義用戶控件擴展它的功能。

要清楚,我希望做以下(或類似):

public class Foo : RichTextBox { } 

我不知道什麼延長這種方法被稱爲或者如果它甚至有一個特定的名稱/分類,但當以這種方式擴展對象時,感覺會更自然,而不是創建新的控件來填充已經臃腫的數百個控件的工具欄。

+0

你顯示的是一個「擴展方法」(https://msdn.microsoft.com/en-us/library/bb383977.aspx)。答案取決於你想要完成什麼。 – itsme86

回答

3

你想被稱爲extension method,例如,這種方法會擴展RichTextBox什麼:

public static class RichTextBoxExtensions 
{ 
    public static void MyCustomMethod(this RichTextBox self) 
    { 
     MessageBox.Show("It works, this textbox has " + self.Text + " as the text!"); 
    } 
} 
+0

謝謝。你不會碰巧知道我應該使用哪個命名空間,或者是否也在'System'下面。 –

+1

@SanuelJackson:正如我在我的回答中提到的:沒有特定的命名空間。如果你不想要其他東西,請使用你的項目。 –

+2

@VisualVincent說的是正確的,命名空間並不重要。你可以使用任何命名空間的擴展方法,所以我傾向於爲它們創建一個新的命名空間,並根據需要將它們帶入我的代碼中。 –

1

只是不喜歡你的字符串的擴展,但使用RichTextBox作爲第一個參數:

public static string MyCustomMethod(this RichTextBox richTextBox) 
{ 
    return richTextBox.Text; 
} 

此外,您不需要與控件具有相同的名稱空間,您可以使用自己的/您的項目的名稱空間而不會出現問題。

+0

幹得好。謝謝。 –