繁体   English   中英

C#泛型滥用?

[英]C# Generics abuse?

我无法弄清楚为什么我得到的错误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
}

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

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

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

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

  T must implement IMobileServiceSyncTable<T> 

但事实并非如此,因为那样

  IMobileServiceSyncTable<IMobileServiceSyncTable<TestDataObject>>

试试这个:

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

问题是你使用T类型IMobileServiceSyncTable<T>约束,其中T再次是类型IMobileServiceSyncTable<T>

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

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

}

请参阅使用类型约束的规范

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM