构造函数调用返回null:该怎么办?

时间:2010-03-19 01:39:39

标签: c# reflection

我的代码如下:

private static DirectiveNode CreateInstance(Type nodeType, DirectiveInfo info) {
    var ctor = nodeType.GetConstructor(new[] { typeof(DirectiveInfo) });

    if(ctor == null) {
        throw new MissingMethodException(nodeType.FullName, "ctor");
    }

    var node = ctor.Invoke(new[] { info }) as DirectiveNode;

    if(node == null) {
        // ???;
    }

    return node;
}

Invoke方法返回的内容不是DirectiveNode或返回null时,我正在寻找要做的事情(例如,抛出什么类型的异常)上面的// ???

(根据方法的合同,nodeType将始终描述DirectiveNode的子类。)

我不确定调用构造函数会返回null,所以我不确定我是否应该处理任何事情,但我仍然希望安全起见并在出现问题时抛出异常

1 个答案:

答案 0 :(得分:5)

您需要确保nodeTypeDirectiveNode

if (!typeof(DirectiveNode).IsAssignableFrom(nodeType))
    throw new ArgumentException("The specified node type is not a 'DirectiveNode'");

此外,您可以(应该)使用Activator.CreateInstance而不是手动查找ConstructorInfo并调用它。它更清洁,更具表现力,更易于维护。