简体   繁体   中英

Generic T in method parameter in C#

I like to do something like this:

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;
}

How to get the "T" in the parameter-list without changing the return type (List)?

Seems to easy... but maybe that's what you were looking for?

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;
}

Note that C# doesn't allow to constrain to enums, so those constraints are more or less the closes you can get.

I think you mixed up the Syntax. I guess you want something like this:

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

In your for each statement you need to exchange typeT with T. Maybe for your internal list you need to call the toString function to get a string.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM