繁体   English   中英

未处理的异常。 System.MissingMethodException:没有为类型定义无参数构造函数

[英]Unhandled exception. System.MissingMethodException: No parameterless constructor defined for type

我对这段代码有问题,但我不知道该怎么做。 你可以帮帮我吗。

错误是:

未处理的异常。 System.MissingMethodException: 没有为类型“Refleksija.Country”定义无参数构造函数。 在 System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache) 在 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
在 System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions) at System.Activator.CreateInstance(Type type) at Refleksija.Program.Main(String[] args) in C:\\Users\\darko.brakovic\\Source\\ Repos\\Refleksija\\Refleksija\\Program.cs:line 14

代码是

class Program
{
    private static void Main(string[] args)
    {

        Assembly executingAssembly = Assembly.GetExecutingAssembly();
        Type countryType = executingAssembly.GetType("Refleksija.Country");
        object countryInstance = Activator.CreateInstance(countryType);

        MethodInfo getCountryInfoMethod = countryType.GetMethod("GetCountryInfo");

        string[] parametri = new string[1];
        parametri[0] = "Srbija";

        string CountryInfo = (string)getCountryInfoMethod.Invoke(countryInstance, parametri);

        Console.WriteLine("CountryInfo: = {0}", CountryInfo);

    }
}
class Country
{
    public string Name { get; set; }
    public int Population { get; set; }
    public Country(string name, int population)
    {
        Name = name;
        Population = population;
    }
    public string GetCountryInfo()
    {
        return "Country " + Name + " has the population of " + Population + ".";
    }
}

正如评论中所指出的, Activator.CreateInstance仅适用于您拥有无参数构造函数的情况(请参阅编译器错误)。 对于您的示例,您可以像这样使用GetConstructor

class Program
{
    private static void Main(string[] args)
    {

        Assembly executingAssembly = Assembly.GetExecutingAssembly();
        Type countryType = executingAssembly.GetType("Refleksija.Country");
        var countryInstance =
            countryType.GetConstructor(new[] {typeof(string), typeof(int)})
                .Invoke(new object[] {"Srbija", 7_000_000});

        MethodInfo getCountryInfoMethod = countryType.GetMethod("GetCountryInfo");

        string CountryInfo = (string) getCountryInfoMethod.Invoke(countryInstance, new object[] { });

        Console.WriteLine("CountryInfo: = {0}", CountryInfo);

    }
}
class Country
{
    public string Name { get; set; }
    public int Population { get; set; }
    public Country(string name, int population)
    {
        Name = name;
        Population = population;
    }
    public string GetCountryInfo()
    {
        return "Country " + Name + " has the population of " + Population + ".";
    }
}

还要注意GetCountryInfo是用参数调用的,但它是一个无参数方法。

暂无
暂无

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

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