一个I防止使用通用的限制特定类型 [英] an I prevent a specific type using generic restrictions

查看:89
本文介绍了一个I防止使用通用的限制特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an overload method - the first implementation always returns a single object, the second implementation always returns an enumeration.

我想使通用的方法。 的过载,并从试图绑定到非枚举法时,泛型类型是枚举的...

I'd like to make the methods generic and overloaded, and restrict the compiler from attempting to bind to the non-enumeration method when the generic type is enumerable...

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

    T[] GetOrAdd<T> (string cachekey, Func<IEnumerable<T>> fnGetItem)
    {
    }
}

要与...

{
    // 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());
}



是我在侵犯该在这里只是简单的糟糕的代码异味,或者是有可能消除歧义上述方法,这样编译器总是会得到调用的代码吧?

Is this just plain bad code-smell that I'm infringing on here, or is it possible to disambiguate the above methods so that the compiler will always get the calling code right?

最多选票的人谁可以制造出比其他任何回答重命名1的方法。

Up votes for anyone who can produce any answer other than "rename one of the methods".

推荐答案

使用只有一个方法,并把它检测到的IEnumerable< T> 动态的情况下,而不是通过一般的约束与虎谋皮。这将是代码味道有对付取决于该对象来存储/检索两种不同的缓存方法是什么枚举与否。此外,仅仅因为它实现的IEnumerable< T> 并不意味着它必然是一个集

Use only one method and have it detect the IEnumerable<T> case dynamically rather than attempting the impossible via generic constraints. It would be "code smell" to have to deal with two different cache methods depending on if the object to store/retrieve is something enumerable or not. Also, just because it implements IEnumerable<T> does not mean it is necessarily a collection.

这篇关于一个I防止使用通用的限制特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆