C#泛型滥用?

时间:2016-04-05 14:31:34

标签: c# generics

我无法弄清楚为什么我收到错误cannot be used as type parameter 't' in the generic type or method...There is no implicit reference conversion from...

这是我的整段代码(简化):

问题在于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
}

3 个答案:

答案 0 :(得分:0)

您的通用约束可能是错误的。对RefreshLocalListFromLocalStore使用以下声明:

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

在你的声明中,表应该是表的表,这没有意义。您仍然可以使用泛型约束来限制您希望为表提供哪种元素,例如,如果表中的元素应该是符合某些IEntity接口的实体。

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

答案 1 :(得分:0)

  T is IMobileServiceSyncTable<TestDataObject>

  T must implement IMobileServiceSyncTable<T> 

但它没有,因为那将是

  IMobileServiceSyncTable<IMobileServiceSyncTable<TestDataObject>>

请改为尝试:

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

答案 2 :(得分:0)

问题是您使用类型IMobileServiceSyncTable<T>约束的T,其中T再次为IMobileServiceSyncTable<T>类型。

对通用接口的类型使用约束

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

}

请参阅使用类型约束的{{3}}。