简体   繁体   中英

Getting 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method

I'm kinda new to C#, and i've seen a few examples on how to do generic handling, but i couldn't find an example in layman's terms

I'll share as to what im trying to do, please any inputs in simple language would be deeply appreciated

static readonly Lazy<SQLiteAsyncConnection> lazyInitializer = new Lazy<SQLiteAsyncConnection>(() =>
    {
        return new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
    });

    public static SQLiteAsyncConnection Database => lazyInitializer.Value;

    public async Task<List<T>> GetItemsAsync<T>()
    {
        var data = await Database.Table<T>().ToListAsync();
        return data;
        //return Database.Table<TodoItem>().ToListAsync();
    }

I'm getting an error as

' T ' must be a non-abstract type with a public parameterless constructor in order to use it as parameter ' T ' in the generic type or method ' SQLiteAsyncConnection.Table<T>() '

I've been going through this Generic in C# , but i'm having a hard time making sense

There is a generic type constraint on the type parameter of Table<T> . You have to ensure then, that any new generic type parameter you introduce that you want to use with Table<T> has a matching (or stricter) type constraint. Here, it's the new() constraint :

public async Task<List<T>> GetItemsAsync<T>() where T: new()
{
    var data = await Database.Table<T>().ToListAsync();
    return data;
    //return Database.Table<TodoItem>().ToListAsync();
}

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