c# - 具有类型约束的扩展方法

标签 c# .net

我有一组这样定义的用户控件..

public class Control1: UserControl, Shop.Stock.IBlue

public class Control2: UserControl, Shop.Stock.IBlue

public class Control2: UserControl, Shop.Stock.IBlue

请注意,其中大约有 200 个,它们在实际项目中的命名更好。

我想在基于 UserControl 的对象上编写一个扩展方法并实现接口(interface) Shop.Stock.IBlue

我不希望扩展方法只是 UserControl

有没有一种方法可以在不添加新基类的情况下做到这一点?

最佳答案

如果我对问题的理解正确,你想定义一个仅适用于实现 IBlueUserControls 的扩展方法。

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

    }

关于c# - 具有类型约束的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9326769/

相关文章:

c# - 在 winforms 生成的 .Designer.cs 文件中修改 Dispose(bool) 时,是否有必要将 Dispose 移动到主代码文件?

c#如何在启动另一个线程之前检查一个线程是否完成

c# - 将锯齿状数组转换为列表

c# - 使 Azure Function 在 ServiceBusTrigger 上顺序运行 - maxConcurrentCalls 不起作用

c# - 在 C# 中模拟非虚拟方法

c# - .NET Core ALINK : warning AL1073: Referenced assembly 'mscorlib.dll' targets a different processor

.net - 如何使用 dotnet 命令创建 nuget 元包?

.net - 如何调试随机挂起

c# - 处理来自引用 dll 的未处理异常

c# - 为什么我的 Parallel.ForAll 调用最终使用单个线程?