Reuse code between methods called multiple types

I am trying to avoid having to write a large number of switch / case (or if / else) statements in one area of ​​my code. Follow the next method:

async internal static Task UndeleteAsync(JObject item, string tableName)
{
    switch (tableName)
    {
        case "QuoteTask":
               var obj = item.ToObject<QuoteTask>();
               var deletedObj = (await MobileService.GetTable<QuoteTask>().IncludeDeleted().Where(x => x.Id == obj.Id).ToListAsync()).FirstOrDefault();
               await MobileService.GetTable<QuoteTask>().UndeleteAsync(deletedObj);                        
        break;
               //Only 26 more tables to go...                
    }        
}

      

This works well, but I have a lot of tables, I am not too familiar with generics, but I thought that maybe something like this would work:

async internal static Task UndeleteAsync<T>(JObject item)
{            
    var obj = item.ToObject<T>();
    var deletedObj = (await MobileService.GetTable<T>().IncludeDeleted().Where(x => (x as BaseObject).Id == (obj as BaseObject).Id).ToListAsync()).FirstOrDefault();
    await MobileService.GetTable<T>().UndeleteAsync(deletedObj);
}

      

Everything seems to be fine, it doesn't give me any compiler errors, but my problem is that I can't call it:

Type tableType = Type.GetType(operation.Table.TableName);
await AzureMobileServices.UndeleteAsync<tableType>(operation.Item);

      

I get the error "tableType" is a variable but is used as "type".

So, I think it is necessary to identify generics at compile time. So I would have to have a massive / case or if / else key to figure out the type anyway.

Can anyone guide me to an elegant way to do this? Or is there no way around it?

+3
c #


source to share


No one has answered this question yet

See similar questions:

868
How do I use reflection to call a generic method?
107
Calling a generic method with a type argument known only at runtime

or similar:

6155
What is the difference between string and string in C #?
1918
Catching multiple exceptions at once?
1507
What is the difference between an abstract function and a virtual function?
1327
Why is it important to override GetHashCode when the Equals method is overridden?
1252
Try to speed up my code?
1240
What is the difference between const and readonly in C #?
1174
Virtual invocation of the participant in the constructor
1169
Calling the basic constructor in C #
1152
Type Check: typeof, GetType or is there?
868
How do I use reflection to call a generic method?



All Articles
Loading...
X
Show
Funny
Dev
Pics