简体   繁体   中英

How to implement a generic c# interface

I am having trouble understanding what my issue is here. CS0452 error, The type T must be ref type in order to use as a parameter...

The error is on this line: Response<T> tableEntity = TC.GetEntity<T>(pk, rk);

using Azure;
using Azure.Data.Tables;

namespace AzureDataTables
{
    public class AzureDataTables<T> : IAzureDataTables<T> where T : class, ITableEntity, new()
    {
        ITableEntity GetTableEntity(string pk, string rk);
    }

    public class AzureDataTables<T> : IAzureDataTables<T> where T : ITableEntity, new()
    {
        public T GetTableEntity(string pk, string rk)
        {
            var tableEntity = TC.GetEntity<T>(pk, rk);
            return tableEntity.Value;
        }
        public TableServiceClient TSC { get; set; } = new TableServiceClient("");
        public TableClient TC => TSC.GetTableClient("");
    }
}

TableClient.GetEntity<T>() has these constraints on the generic type:

where T : class, ITableEntity, new();

You're missing the class constraint on your own generic type as well to be able to use it with that function.

You need to use a concrete type in the implementation of the Interface if it has a generic type in it's contract. Here's a working example:

using Azure;
using Azure.Data.Tables;

namespace AzureDataTables
{
    public interface IAzureDataTables<T> where T : class, ITableEntity, new()
    {
        ITableEntity GetTableEntity(string pk, string rk);
    }

    public class AzureDataTables<T> : IAzureDataTables<T> where T : class, ITableEntity, new()
    {
        public ITableEntity GetTableEntity(string pk, string rk)
        {
            Response<T> tableEntity = TC.GetEntity<T>(pk, rk);
            return tableEntity.Value;
        }

        public TableServiceClient TSC { get; set; } = new TableServiceClient("");
        public TableClient TC => TSC.GetTableClient("");
    }
}

The methode you are calling is TableClient.GetEntity this has a constraint where T: class, Azure.Data.Tables.ITableEntity, new(); .
Your methode does not have the constraint class so when the compiler checks if your T can be used for the methode it does not comply with all the constraints.

If you change

public class AzureDataTables<T> : IAzureDataTables<T> where T : ITableEntity, new()

To

public class AzureDataTables<T> : IAzureDataTables<T> where T : class, ITableEntity, new()

It will compile.

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