相关疑难解决方法(0)

使用反射在内部类中使用参数实例化构造函数

我有类似的东西:

object[] parameter = new object[1];
parameter[0] = x;
object instantiatedType =
Activator.CreateInstance(typeToInstantiate, parameter);
Run Code Online (Sandbox Code Playgroud)

internal class xxx : ICompare<Type>
{
    private object[] x;

    # region Constructors

    internal xxx(object[] x)
    {
        this.x = x;
    }

    internal xxx()
    {
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

我得到:

抛出异常:System.MissingMethodException:找不到类型为"xxxx.xxx"的构造函数..

有任何想法吗?

c# reflection

51
推荐指数
3
解决办法
3万
查看次数

如何通过反射使用内部构造函数创建类的对象实例?

例:

class Program
{
    static void Main(string[] args)
    {
        var myClass = Activator.CreateInstance(typeof(MyClass));
    }
}

public class MyClass
{
    internal MyClass()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

例外:

system.missingMethodException而

没有为此对象定义的无参数构造函数.

解:

var myClass = Activator.CreateInstance(typeof(MyClass), nonPublic:true);
Run Code Online (Sandbox Code Playgroud)

我无法理解,为什么我无法使用内部构造函数在程序集内创建实例.此构造函数应该在执行程序集中可用.对于这个程序集,它应该像public一样工作.

c# reflection instance

5
推荐指数
1
解决办法
6578
查看次数

标签 统计

c# ×2

reflection ×2

instance ×1