How to call a generic extension method with reflection?

后端 未结 4 1764
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 17:30

I wrote the extension method GenericExtension. Now I want to call the extension method Extension. But the value of methodInfo is alway

4条回答
  •  鱼传尺愫
    2020-12-06 18:12

    Building off of @Mike Perrenoud's answer, the generic method I needed to invoke was not constrained to the same type as the class of the extension method (i.e. T is not of type Form).

    Given the extension method:

    public static class SqlExpressionExtensions
    {
        public static string Table(this IOrmLiteDialectProvider dialect)
    }
    

    I used the following code to execute the method:

    private IEnumerable GetTrackedTableNames(IOrmLiteDialectProvider dialectProvider)
    {
        var method = typeof(SqlExpressionExtensions).GetMethod(nameof(SqlExpressionExtensions.Table), new[] { typeof(IOrmLiteDialectProvider) });
    
        if (method == null)
        {
            throw new MissingMethodException(nameof(SqlExpressionExtensions), nameof(SqlExpressionExtensions.Table));
        }
    
        foreach (var table in _trackChangesOnTables)
        {
            if (method.MakeGenericMethod(table).Invoke(null, new object[] { dialectProvider }) is string tableName)
            {
                yield return tableName;
            }
        }
    }
    

    where the types defined in _trackChangesOnTables are only known at runtime. By using the nameof operator, this protects against exceptions at runtime if the method or class is ever removed during refactoring.

提交回复
热议问题