开发者

Constructor invocation returned null: what to do?

I have code which looks like:

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

    if(ctor == null) {
        throw new MissingMet开发者_运维知识库hodException(nodeType.FullName, "ctor");
    }

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

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

    return node;
}

I am looking for what to do (e.g. what type of exception to throw) when the Invoke method returns something which isn't a DirectiveNode or when it returns null (indicated by // ??? above).

(By the method's contract, nodeType will always describe a subclass of DirectiveNode.)

I am not sure when calling a constructor would return null, so I am not sure if I should handle anything at all, but I still want to be on the safe side and throw an exception if something goes wrong.


You need to ensure that nodeType is a DirectiveNode:

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

Also, you can (should) use Activator.CreateInstance instead of manually finding the ConstructorInfo and invoking it. It's cleaner, more expressive, and more maintainable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜