相关疑难解决方法(0)

我使用通用限制来阻止特定类型

我有一个重载方法 - 第一个实现总是返回一个对象,第二个实现总是返回一个枚举.

我想使方法通用重载,并限制编译器在泛型类型可枚举时尝试绑定到非枚举方法...

class Cache
{
    T GetOrAdd<T> (string cachekey, Func<T> fnGetItem)
        where T : {is not IEnumerable}
    {
    }

    T[] GetOrAdd<T> (string cachekey, Func<IEnumerable<T>> fnGetItem)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

与...一起使用

{
    // The compile should choose the 1st overload
    var customer = Cache.GetOrAdd("FirstCustomer", () => context.Customers.First());

    // The compile should choose the 2nd overload
    var customers = Cache.GetOrAdd("AllCustomers", () => context.Customers.ToArray());
}
Run Code Online (Sandbox Code Playgroud)

这只是一个简单的坏代码 - 我在这里侵犯了代码,或者是否可以消除上述方法的歧义,以便编译器始终可以获得正确的调用代码?

除了"重命名其中一种方法"之外,任何可以产生任何答案的人的投票.

c# generics restriction

6
推荐指数
3
解决办法
379
查看次数

标签 统计

c# ×1

generics ×1

restriction ×1