【发布时间】:2015-06-13 15:39:11
【问题描述】:
问题:我如何传达我的泛型方法可以与哪些类型一起使用?
我想使用泛型来创建与三种或四种不同类型(而不是所有类型)兼容的方法。这是一个人为的例子:
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 和 string,但在我的真实代码中它们将是类对象。这个功能很好,但是对于其他程序员他们不知道他们可以把什么放入
有什么方法可以让智能感知“看到”它并能够将它传达给我的代码的用户。
我正在尝试摆脱这种风格:
public List<int> GetAllInt();
public List<int> GetAllString();
public List<int> GetAllBool();
因为它会使界面膨胀。我希望他们能够看到他们可以执行的一小部分功能,然后在他们选择活动后选择类型,所以像 GetAll
我已经看到 where T : IMyInterface 确实限制了他们可以发送的内容,但它并没有传达他们可以发送的内容。
【问题讨论】:
-
为什么不写3个或4个方法呢?这违反了泛型的概念。
-
@SeanVieira 字符串未被覆盖。
-
这不是“泛型”;它是类型特异性的鞋拔到一个通用 API
-
同意@Daniel - 这似乎是 OP 正在寻找的东西的 type 相当接近的近似值(但从编辑看来并非如此)