开发者

C# Get Type of IEnumerable<TModel>

I have a method to which I pass an IEnumerable<TModel>. Then depending on the type of TModel, the method carries out a set of instructions as below:

    public void MyMethod<TModel>(IEnumerable<TModel> items) where TModel : class
    {
        int operationType;
        switch (typeof(TModel))
        {
            case typeof(MyModelOne):
                operationType = 1;
                break;
            case typeof(MyModelTwo):
                operationType = 2;
                break;
            case typeof(MyModelThree):
                operationType = 3;
              开发者_Go百科  break;
            default:
                throw new Exception("The collection model passed to MyMethod is not recognized");
        }
        ...
    }

This doesnt work, I get the error:

There is no application variable or memeber 'TModel'


You can't switch on a Type variable. Replace it with cascading if statements.

 if (typeof(TModel) == typeof(MyModelOne)) {
    operationType = 1;
 } else if (typeof(TModel) == typeof(MyModelTwo)) {
    operationType = 2;
 } // ...


switch statements only work on constant values, such as strings, integers and other fundamental types. Type is not a constant value, so it can't be used in a switch block.

An equivalent operation is a block of if statements or using a dictionary with a Type used as the key.


The other answers here are true, but you should probably take a step back and look at why you're doing this. The whole point of generics is that they should be generic. If you are doing different things based on the type, then maybe a generic method isn't the way to go - maybe overloaded methods are right for you.

Or maybe the types that you want to accept can implement the same interface, and you can make calls on them based on the interface as opposed to checking the type manually. For example:

interface IDoesSomething
{
  void DoSomething();
}

void MyMethod<T>(IEnumerable<T> objects)
  where T : IDoesSomething
{
  foreach (T t in objects)
  {
    t.DoSomething();
  }
}


You can only switch on integral and string types. In this case, you'll have to use if/else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜