如何将私有方法称为一个类的基础?
这是我的结构的基本示例(该代码包含在参考中):
public abstract class Something {
}
internal class ImplBase : Something {
private void CallMe(string s) {}
}
internal class RealImpl : ImplBase {
}
到目前为止,我有一个RealImpl
可见的实例Something
。如何访问该方法CallMe
?
我在这里尝试这段代码:
Type type = obj.GetType(); // returns RealImpl
bool supported = false;
// a loop to be a little more flexible
for(Type t = type; t.Name != "Object"; t = t.BaseType) {
if(t.Name == "ImplBase") {
supported = true;
type = t;
break;
}
}
if(supported) {
var callme = type.GetMethod("CallMe", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string) }, new ParameterModifier[] {});
callme.Invoke(obj, new object[] { "hi" });
} else {
throw new NotSupportedException("The type " + type.Name + " is not supported.");
}
如果我注释掉,type = t;
我会得到callme
一个null
价值。如果我使用像这里这样的代码,我会得到一个关于 internal 的异常大喊大叫NullReferenceException
。
NullReferenceException
到目前为止,我的hack 我在 lib 内部生成了一个我的错。上面的代码现在已经修复(简化时有 3 个错误)。