Pass concrete object type as parameter for generic method

前端 未结 1 914
眼角桃花
眼角桃花 2020-12-03 12:48

I have an API using generic method as follow

public static class DataProvider
{
    public static Boolean DeleteDataObject(Guid uid, IDbConnection d         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 13:03

    I suspect you want something like this:

    public static Boolean PurgeDataObject(this IDataObject dataObject, Guid uid)
    {
        return PurgeDataObjectImpl((dynamic) dataObject, uid);
    }
    
    private static Boolean PurgeDataObjectImpl(T dataObject, Guid uid)
        where T : IDataObject
    {
        return DataProvider.DeleteDataObject(uid, DataProvider.GetConnection());
    }
    

    That uses dataObject dynamically, getting the "execution-time compiler" to perform type inference to work out T.

    You could just use reflection to do this yourself, using MethodInfo.MakeGenericMethod - but this way is certainly less code.

    0 讨论(0)
提交回复
热议问题