How to create an object instance of class with int

2019-02-23 00:02发布

Example:

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

public class MyClass
{
    internal MyClass()
    {
    }
}

Exception:

System.MissingMethodException

No parameterless constructor defined for this object.

Solution:

var myClass = Activator.CreateInstance(typeof(MyClass), nonPublic:true);

I cannot understand, why I cannot create an instance inside the assembly with internal constructor. This constructor should be available inside the execution assembly. It should work like public for this assembly.

2条回答
2楼-- · 2019-02-23 00:29

It is not that impossible. you've to tell it is not a public.

var myClass = Activator.CreateInstance(typeof(MyClass), true);//say nonpublic
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-23 00:35

The constructor inside your MyClass is Internal try to change to public

public class MyClass
{
    public MyClass()
    {
    }
}

or

Pass true to CreateInstance

var myClass = Activator.CreateInstance(typeof(MyClass),true );
查看更多
登录 后发表回答