调用"内部的extern"使用反射构造 [英] Invoke "internal extern" constructor using reflections
问题描述
我有下面的类(通过反射看到)
I have following class (as seen through reflector)
public class W : IDisposable
{
public W(string s);
public W(string s, byte[] data);
// more constructors
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern W(string s, int i);
public static W Func(string s, int i);
}
我想称之为内部外部的构造或FUNC。使用反射
I am trying to call "internal extern" constructor or Func using reflections
MethodInfo dynMethod = typeof(W).GetMethod("Func", BindingFlags.Static);
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(null, argVals);
和
Type type = typeof(W);
Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
ConstructorInfo dynMethod = type.GetConstructor(BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, argTypes, null);
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(null, argVals);
unfortunantly这两个变种上升的NullReferenceException尝试调用的时候,所以,我必须做一些错误的?
unfortunantly both variants rise NullReferenceException when trying to Invoke, so, I must be doing something wrong?
推荐答案
使用激活
通常是好主意,但你必须使用一个呼叫拥有的BindingFlags因为使用它的内部构造输入参数。
Using Activator
is usually good idea but you have to use a call that has BindingFlags as input parameter to use it for internal constructor.
在你的代码有几个不同的错误。您在这两个片段使用错误的BindingFlags并在构造函数片断,使用错误的Invoke方法。下面是代码应工作:
In you code there are a few of different mistakes. You use wrong BindingFlags in both snippets and in constructor snippet you used wrong Invoke method. Here is code that should work:
MethodInfo dynMethod = typeof(W).GetMethod("Func", BindingFlags.Static | BindingFlags.Public);
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(null, argVals);
Type type = typeof(W);
Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
ConstructorInfo dynMethod = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, argTypes, null);
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(argVals);
Activator.CreateInstance(typeof(W), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { "hi", 1 }, null);
这篇关于调用"内部的extern"使用反射构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!