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

str*_*ger 3 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;
}
Run Code Online (Sandbox Code Playgroud)

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

(通过方法的契约,nodeType将始终描述的子类DirectiveNode.)

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

Sam*_*ell 5

你需要确保这nodeType是一个DirectiveNode:

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

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