-1
问题:如何沟通可以使用哪种类型的泛型方法?C#泛型但通信兼容类型?
我想使用泛型来创建与三种或四种不同类型(而不是所有类型)兼容的方法。这里是一个人为的例子:
public List<T> GetAll<T>()
{
Type typeParameterType = typeof(T);
if(typeParameterType == typeof(string))
{
var myList = new List<string>() { "one", "two", "three" };
return myList.Cast<T>().ToList();
}
else if (typeParameterType == typeof(int))
{
var myList = new List<int>() { 1, 2, 3 };
return myList.Cast<T>().ToList();
}
return new List<T>();
}
var intResult = GetAll<int>();
var stringResult = GetAll<string>();
这里我使用int和字符串,但在我真正的代码,他们会是类对象。这个功能很好,但是对于其他程序员来说,他们不知道他们可以把什么放入<T>,因为它支持的内部逻辑是内部的。
有什么办法,我可以说GETALL <INT>,GETALL <串>,GETALL <布尔>等以这样一种方式,智能感知会“看到”它,并能够将其传达给我的代码的用户。
我试图摆脱这种款式远:
public List<int> GetAllInt();
public List<int> GetAllString();
public List<int> GetAllBool();
因为它使腌出接口。我希望他们能够看到他们可以做的一小部分功能,然后在他们选择了该活动后选择类型,所以像GetAll <int>()似乎对我来说更清洁。但没有办法沟通什么是兼容的是一个路障。
我已经看到了其中T:IMyInterface的这不会限制他们可以送什么,但它并不沟通它是什么,他们可以发送。
为什么你不只是写3或4个方法?这违反了泛型的概念。 –
[How to define generic type limit to primitive types?](http://stackoverflow.com/questions/805264/how-to-define-generic-type-limit-to-primitive-types) –
@ SeanVieira字符串不被覆盖。 –