应该Assembly.GetExecutingAssembly().CreateInstance在这里抛出一个异常

本文关键字:异常 一个 在这里 Assembly GetExecutingAssembly CreateInstance 应该 | 更新日期: 2023-09-27 18:06:26

我是新手,所以这可能是一个"愚蠢的问题",或者可能不适合在这里,请酌情建议。

我正在探索c#的一些特性,这周我正在研究反射。当我阅读http://msdn.microsoft.com/en-us/library/145sfyea.aspx时,我感到困惑,从我可以告诉我没有得到MissingMethodException(没有找到匹配的构造函数),当我认为我应该。

问题:这段代码应该在指定点抛出异常吗?

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Test
{
    abstract class Vehicle
    {
        public string type { get; set; }
    }
    class Van : Vehicle
    {
        public Van()
        {
            System.Console.WriteLine("van!");
            this.type = "van";
            // ...
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<String> things = new List<String>();
            things.Add("Van");
            things.Add("Car");
            List<Vehicle> inventory = new List<Vehicle>();
            foreach (String s in things)
            {
                Vehicle vehicle = Assembly.GetExecutingAssembly().CreateInstance("Test" + "." + s, true) as Vehicle;
                if (vehicle != null)
                {
                    inventory.Add(vehicle);
                }
                else
                {
                    System.Console.WriteLine("Should an attempt to create an instance of"+ "Test" + "." + s+ " have thrown an exception? " );
                };
            }
            Console.Read();
            Console.Read();
        }
    }
}

应该Assembly.GetExecutingAssembly().CreateInstance在这里抛出一个异常

No。如果存在Test.Car类型,但没有公共无参数构造函数,则会得到MissingMethodException。如果找不到类型,则返回null;如果找到了类型,但是无法找到与您提供的参数列表匹配的公共构造函数,则抛出 MissingMethodException

从MSDN:


类型:系统。对象
使用默认构造函数创建的指定类型的实例;如果没有找到typeName,则为null。

可以,但前提是它不能在现有类型中找到构造函数。(即。这是私人的)。在您的代码中,没有'Car'类,因此没有类型供其搜索构造函数,因此返回一个空对象。

这会抛出MissingMethodException:

class Car : Vehicle {
    private Car() { // I'm private and you cannot find me.
        System.Console.WriteLine("car!");
        this.type = "car";
    }
}

如果不能解析类型的构造函数,那么当然,我预计会出现异常。但是,如果找不到所讨论的类型,该方法在文档中会返回null。

有像Type.GetType()这样的方法接受一个布尔标志,它决定是否应该引发异常…我想这个特殊的方法在某种程度上会从中受益,但是您总是可以在尝试创建实例之前调用Type.GetType(),并指定如果无法定位类型则需要异常。