繁体   English   中英

继承类C#反射的构造函数的调用

[英]Calling Constructor of inheriting class C# reflection

我正在使用反射来加载我的程序集。

下面是我的汇编代码,将通过反射加载:

using BaseDll;

namespace CustomLibrary
{
    public class CustomClass : BaseClassofDll
    {
        // Creating all constructors as of base class
        public CustomClass() : base() { }
        public CustomClass(string s1, string s2) : base(s1,s2) { }
        public CustomClass(string s1, string s2, object obj) : base(s1, s2, obj) { }

        public override void Method1() { }
        public override void Method2() { }
    }
}

反射码:

namespace MyLibrary
{
    public class MyClass
    {
        public void CreateAssemblyClass()
        {
            string dllPath = "C:\Users\xyz\AppData\Local\Temp\CustomLibrary.dll"
            Assembly asm = Assembly.LoadFrom(dllPath);
            // asm is loaded with correct dll

            Type t = asm.GetType("CustomLibrary.CustomClass");
            // t is initialized with correct class

            object[] constructorParameters = new object[2];
            constructorParameters[0] = "123";   // First parameter.
            constructorParameters[1] = "456";   // Second parameter.

            dynamic result = Activator.CreateInstance(t, constructorParameters);
            // Get Exception here : Constructor on type 'CustomLibrary.CustomClass' not found."

            t.GetConstructors();
            // This gives only single constructor of type ctor()
            // My constructor with 2 or 3 parameters is not found. 

            ConstructorInfo ctor = t.GetConstructor(new[] { typeof(string),typeof(string) });
            // This gives null
        }
    }
}

如何使用参数化构造函数创建CustomClass的insatence。 这是必需的,因为我要覆盖CustomClass中的2个方法,因此我想使用CustomClass而不是BaseClassofDll。

编辑:由于你们中的许多人都要求共享BaseClassofDll的代码,所以我告诉你BaseDll是一个第三方dll。 在查看其定义时,如下所示:

public class BaseClassofDll
{
    public BaseClassofDll();
    public BaseClassofDll(string s1);
    public BaseClassofDll(object obj, string s1);
    public BaseClassofDll(string s1, string s2);
    public BaseClassofDll(object obj, string s1, string s2);

    /*****Other methods ***/
}

使用asm.CreateInstance(“ CustomLibrary.CustomClass”); 我认为我应该工作。 传递您的参数。我已经对其进行了硬编码。

不带参数的GetConstructors函数将仅显示公共的非静态构造函数。 请验证您的实际实现符合以下条件:

Default flags: BindingFlags.Public | BindingFlags.Instance

MSDN:Type.GetConstructors方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM