【问题标题】:C# generics syntax for multiple type parameter constraints [duplicate]多类型参数约束的C#泛型语法[重复]
【发布时间】:2010-11-01 05:21:06
【问题描述】:

可能重复:
Generic methods and multiple constraints

我需要一个具有两个类型约束的泛型函数,每个约束都继承自不同的基类。我知道如何用一种类型做到这一点:

void foo<T>() where T : BaseClass

但是,我不知道如何使用两种类型来做到这一点:

void foo<TOne, TTwo>() where TOne : BaseOne // and TTwo : BaseTwo ???

你是怎么做到的? (使用 .NET 2)

【问题讨论】:

    标签: c# generics


    【解决方案1】:
    void foo<TOne, TTwo>() 
       where TOne : BaseOne
       where TTwo : BaseTwo
    

    更多信息在这里:
    http://msdn.microsoft.com/en-us/library/d5x73970.aspx

    【讨论】:

    • 如果您不想全部阅读,请搜索“约束多个参数”。
    • 是否有可能有一个约束来做到这一点:void foo&lt;TOne, TTwo&gt;() where TOne : Class where TTwo : Class where TOne != TTwo 所以基本上我们不知道 TOne 和 Ttwo 是什么,除了它们是引用类型但不能相同
    • @IronHide:我很想在这里被证明是错误的……但我 99% 确信这是不可能的 :)
    • 以及如何将 ExtensionMethod 与多个泛型一起使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多