문제

In this function:

    public List<T> getX<T>(SPListItemCollection itemCollection, List<T> itemList, Report RO, WebpartSettings WPS, bool isFolder)
    {
        foreach (SPListItem item in itemCollection)
        {
            if (have_permissions_for_item(WPS.EDIT_MODE, item, RO))
            {
                itemList.Add(isFolder ? (T)item.Folder : (T)item);
            }
        }
        return itemList;
    }

which uses parametric polymorphism, I get a itemcollection and browse through it and add it to a list if it as the right permissions, then return the list. The list being returned is of type T, so it could be of type either SPFolder or SPListItem based on my code.

The item in the for loop is already type SPListItem, and if T was of type SPFolder then I have to call the .Folder method on the item. I can't just detect this, so I had to use a helper variable to decide if I need to use it.

But the problem is even though I do this I still get an error with trying to cast it to type T.

T will be SPFolder when I call the .Folder method and T will be the type SPListItem otherwise.

Does anyone see a fix for this?

Thanks.

도움이 되었습니까?

해결책

Since T could in theory be any type, Visual Studio doesn't know if there's a way to cast from either type to T. You could try inserting an (object) cast:

itemList.Add(isFolder ? (T)(object)item.Folder : (T)(object)item);

As long as T is the correct type, you should be fine.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top