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

时间:2011-08-22 18:07:38

标签: c#

我很新,所以这可能是一个“愚蠢的问题”,或者可能不合适,请酌情提出建议。

我正在探索一些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();
        }

    }

}

3 个答案:

答案 0 :(得分:4)

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

来自MSDN:

  

返回值
  键入:System.Object
  使用默认构造函数创建的指定类型的实例;如果找不到 typeName ,则返回null。

请参阅this ideone example

答案 1 :(得分:1)

它会,但只有在现有类型中找不到构造函数时才会这样。 (即它是私人的)。在你的代码中,没有'Car'类,因此没有类型可以搜索构造函数,因此返回一个null对象。

这会抛出一个MissingMethodException:

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

答案 2 :(得分:0)

如果类型的构造函数无法解析那么肯定,我期待一个例外。但是如果找不到有问题的类型,则该方法被记录为返回null。

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

相关问题