如何在接口为private/internal时调用显式接口实现方法?

How to invoke the explicitly interface implement method while the interface is private/internal?

我想调用 System.Data.Linq.SqlClient.SqlProvider class 中定义的方法 ICompiledQuery IProvider.Compile(Expression query)

但是IProvider接口是内部的,所以我不能做转换。有什么方法可以调用该方法吗?

您可以使用反射获取方法并调用它。

// Some test stuff, replace this with your own.
Expression e = null;
SqlProvider p = new SqlProvider();

// Get the IProvider interface
var iProvider = typeof(SqlProvider).FindInterfaces((t, o) => t.FullName == "System.Data.Linq.Provider.IProvider", null).FirstOrDefault();

if (iProvider != null)
{
    // Get the Compile method on the interface
    MethodInfo m = iProvider.GetMethod("Compile");

    // Call it!
    var output = m.Invoke(p, new object[] { e });
}