简体   繁体   中英

C# Generics abuse?

I can't figure out why I am getting the error cannot be used as type parameter 't' in the generic type or method...There is no implicit reference conversion from...

Here is my entire piece of code (simplified):

The problem is on the line RefreshLocalListFromLocalStore(TestDataObjectTable);

using System;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using Microsoft.WindowsAzure.MobileServices.Sync;

public class TestDataObject
{
    #region Properties

    public string Id { get; set; }

    #endregion
}

public class TestDatabaseManager
{
    public MobileServiceClient Client;

    private IMobileServiceSyncTable<TestDataObject> TestDataObjectTable;

    public TestDatabaseManager()
    {
        CurrentPlatform.Init();
        Client = new MobileServiceClient("SomeUrl");
        var store = new MobileServiceSQLiteStore("SomePath");
        store.DefineTable<TestDataObject>();

        TestDataObjectTable = Client.GetSyncTable<TestDataObject>();

        RefreshLocalListFromLocalStore(TestDataObjectTable);
    }

    #region Methods

    public async void RefreshLocalListFromLocalStore<T>(T table) where T : IMobileServiceSyncTable<T>
    {
        try
        {
            await table.ToListAsync();
        }
        catch (Exception e)
        {
        }
    }

    #endregion
}

Your generic constraint is probably wrong. Use the following declaration for RefreshLocalListFromLocalStore :

public async void RefreshLocalListFromLocalStore<T>(IMobileServiceSyncTavble<T> table)

In your declaration, the table should have been a table of tables, which does not make sense. You can use the generics constraints still to limit what kind of elements you want to have for your table, for example if the elements in the table should be entities complying with some IEntity interface.

public async void RefreshLocalListFromLocalStore<T>(IMobileServiceSyncTavble<T> table) where T : IEntity
  T is IMobileServiceSyncTable<TestDataObject>

  T must implement IMobileServiceSyncTable<T> 

but it doesn't, because that would be

  IMobileServiceSyncTable<IMobileServiceSyncTable<TestDataObject>>

Try this instead:

public async void RefreshLocalListFromLocalStore<T>(IMobileServiceSyncTable<T> table) 
{
    ...
}

The problem is you're using T with constraint of Type IMobileServiceSyncTable<T> where T is again of Type IMobileServiceSyncTable<T> .

Use constraints on the type for generic interface

public async void RefreshLocalListFromLocalStore<T>(IMobileServiceSyncTable<T> table) 
                                                                  where T : TestDataObject
{

}

See specification of using Type constraints.

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