Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

c# - Method parameter to accept multiple types

I'm developing an application which in I got multiple types of RichTextBoxs which I've customized (RichTextBox,RichAlexBox,TransparentRichTextBox).

I want to create a method to accept all those types plus some other parameters.

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

I've searched through StackOverFlow and found some answers like this which I couldn't figure out how to use them to solve my problem

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

I also tried overloading as this answer offers,

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
  }

But I encounter this error

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

Here's some other Q&A I checked:

Generic method with multiple constraints

Can I create a generic method that accepts two different types in C#

C# generic method with one parameter of multiple types

Any suggestion would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that TransparentRichTextBox and RichAlexBox are both subtypes of RichTextBox, then you only need one method signature:

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

Otherwise, you will need to implement the method for every overload:

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...