简体   繁体   中英

Extension Method with Type Constraints

I have a set of user controls which are defined like so..

public class Control1: UserControl, Shop.Stock.IBlue

public class Control2: UserControl, Shop.Stock.IBlue

public class Control2: UserControl, Shop.Stock.IBlue

note there are about 200 of these and they are named better in the real project.

I want to write an extension method on objects which are based off UserControl and implement the interface Shop.Stock.IBlue

I don't want the extension method to just be of UserControl

Is there a way of doing this with out adding in a new base class?

If I'm understanding the question correctly, you want to define an extension method which is only applicable to UserControls which implement IBlue .

   public static void Foo<T>( this T obj )
       where T : UserControl, IBlue
    {

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM