方法参数以接受多个类型

本文关键字:类型 参数 方法 | 更新日期: 2023-09-27 18:19:10

我正在开发一个应用程序,在我有多种类型的RichTextBox,我已经定制了(RichTextBox,RichAlexBox,TransparentRichTextBox)

我想创建一个方法来接受所有这些类型和一些其他参数。

private void ChangeFontStyle(RichTextBox,RichAlexBox,TransparentRichTextBox rch,
                                                         FontStyle style, bool add)
{
  //Doing somthing with rch.Rtf
}

我搜索了StackOverFlow,发现了一些类似这样的答案,但我不知道如何使用它们来解决我的问题

void foo<TOne, TTwo>()  //There's just one parameter here
   where TOne : BaseOne //and I can't figure out how to define my other two parameters        
   where TTwo : BaseTwo

我也试过超载这个答案提供,

private void ChangeFontStyle(TransparentRichTextBox rch, FontStyle style, bool add);
private void ChangeFontStyle(RichAlexBox rch, FontStyle style, bool add);
private void ChangeFontStyle(RichTextBox rch,FontStyle style, bool add)
  {
    //Some codes
  }

但是我遇到了这个错误

'ChangeFontStyle(RichAlexBox, FontStyle, bool)' 
         must declare a body because it is not marked abstract, extern, or partial

这里是我检查过的一些其他问题:

具有多个约束的泛型方法

我可以在c#中创建一个接受两种不同类型的泛型方法吗

一个多类型参数的c#泛型方法

方法参数以接受多个类型

假设TransparentRichTextBoxRichAlexBox都是RichTextBox,那么你只需要一个方法签名:

private void ChangeFontStyle(RichTextBox rch, FontStyle style, bool add)
{
    //Doing somthing with rch.Rtf
}

否则,您需要为每个重载实现该方法:

private void ChangeFontStyle(TransparentRichTextBox rch, FontStyle style, bool add)
{
    //Some codes
}
private void ChangeFontStyle(RichAlexBox rch, FontStyle style, bool add)
{
    //Some codes
}
private void ChangeFontStyle(RichTextBox rch,FontStyle style, bool add)
{
    //Some codes
}

如果您正确地使用了继承,则不需要泛型或重载:

class RichTextBox
{
     // implementation
}
class RichAlexBox : RichTextBox
{
     // implementation
}
class TransparentRichTextBox : RichTextBox
{
     // implementation
}
// allows passing in anything that inherits from RichTextBox
private void ChangeFontStyle(RichTextBox rch, FontStyle style, bool add)
{
     // implementation
}

作为@dotnetkid建议,另一个选择是使ChangeFontStyle在RichTextBox类中的方法,并使其虚拟,以便您可以在需要时覆盖它:

class RichTextBox
{
     public virtual void ChangeFontStyle(FontStyle style, bool add)
     {
         // implementation
     }
     // implementation
}
class RichAlexBox : RichTextBox
{
     // uses the inherited ChangeFontStyle
     // implementation
}
class TransparentRichTextBox : RichTextBox
{
     public override void ChangeFontStyle(FontStyle style, bool add)
     {
         // TransparentRichTextBox-specific implementation
     }
     // implementation
}

当重载一个方法时这样做。

private void ChangeFontStyle(TransparentRichTextBox rch, FontStyle style, bool add)
{
   // your code
}
private void ChangeFontStyle(RichAlexBox rch, FontStyle style, bool add) 
{
   // your code
}
private void ChangeFontStyle(RichTextBox rch,FontStyle style, bool add)
{
   // your code
}

或者你可以直接使用Control class作为参数,像这样尝试

 private void ChangeFontStyle(Control control,FontStyle style, bool add)
 {
       // your code
 }

您可以传递任何您想要的控件,如TextBox, RichTextBox, ComboBox