我有一个框架允许我通过键盘访问项目中对象的状态和方法。它很大程度上依赖于ImpromptuInterface,这非常快速且灵活。使用ImpromptuInterface调用基类的私有成员
例如,我使用Impromptu.InvokeMember(myObject, methodName, castParameters)
调用方法。它对公共和私人成员非常有用,但是当我尝试拨打myObject
基类的私人成员时,我得到了Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'MyType.MyMethod(Something)' is inaccessible due to its protection level
。
,揭示了问题的最简单的代码:
public class MainClass
{
public static void Main(string[] args)
{
var type = new PublicType();
var other = new OtherType();
Console.WriteLine(Impromptu.InvokeMember(other, "Method", 2)); //works
Console.WriteLine(Impromptu.InvokeMember(type, "Method", 2)); //crash
}
}
public class PublicType : OtherType
{}
public class OtherType
{
private bool Method(object a)
{
return a != null;
}
}
我明白为什么有这样的问题,我可以看到一些可能的解决方案,像在寻找类,其中定义的方法,并试图把我的对象投给那个班,但这很麻烦。
有没有简单的解决方案,最好严格依据Impromptu?
使用ILSpy来查看'Impromptu.InvokeMember'是如何实现的 – sll
好吧,它是开源的,但相当复杂。我不是真的进入DLR。 –
你可以试试这个,而不是使用隐式类型变量,试试下面的OtherType type = new PublicType(); OtherType other = new OtherType();我试图看看Impromptu是否像反射绑定一样使用DeclaredOnly。 – humblelistener