C#中方法参数中的泛型T

时间:2012-06-24 20:16:33

标签: c# .net generics methods generic-list

我喜欢这样做:

public static List<string> ItemsOfEnum(T typeT)
{
    List<string> items = new List<string>();
    foreach (typeT tItem in Enum.GetValues(typeof(typeT)))
       items.Add(tItem);
    return items;
}

如何在参数列表中获取“T”而不更改返回类型(List)?

3 个答案:

答案 0 :(得分:6)

似乎很容易......但也许这就是你要找的东西?

public static List<string> ItemsOfEnum<typeT>()
        where typeT: struct, IComparable, IFormattable, IConvertible {
    List<string> items = new List<string>();
    foreach (typeT tItem in Enum.GetValues(typeof(typeT)))
       items.Add(tItem.ToString());
    return items;
}

请注意,C#不允许约束枚举,因此这些约束或多或少都可以获得关闭。

答案 1 :(得分:1)

我认为你混淆了语法。我想你想要这样的东西:

public static List<string> ItemsOfEnum<T>(T inputList) {...}

在你的每个语句中你需要用T交换typeT。对于你的内部列表,你需要调用toString函数来获取一个字符串。

答案 2 :(得分:0)

  public static List<string> itemsofenum<typet>()
  { ... }