Generic method with generic interface

181 Views Asked by At

I have this method

public static void ReadExcelToKeyableList<T, TKey>() where T : IKeyable<TKey>, IExcel
{
    List<T> keyableList = GetList(typeof(T));
    T getKeyable;

Part of the code in the method is this:

        foreach (IExcel xl in toList)
            if (xl is T)
            {
                (keyableList[keyableList.IndexOf(getKeyable)] = (xl as T)).Update();
            }

And i get the next error

The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint


I've tried to change the code to this one:

(keyableList[keyableList.IndexOf(getKeyable)] = (xl as IKeyable<TKey>)).Update();

And now i get this error:

Cannot implicitly convert type 'DataService.Classes.IKeyable' to 'T'. An explicit conversion exists (are you missing a cast?)


Why can't i convert IKeyable to T even if i set where T : IKeyable<TKey>?

Anyone have any idea how can i solve this?

0

There are 0 best solutions below