如何解决:转换运算符无法从接口类型转换

时间:2016-01-02 11:47:14

标签: c# .net vb.net interface com

我已经包装了 INetFwRule 成员,我已将这些属性放在名为FirewallRule的自定义类型中,并且为了节省时间而优先考虑执行从INetFwRuleFirewallRule的转换时代码的其他部分我尝试编写此隐式转换器:

C#:

public static explicit operator FirewallRule(INetFwRule rule) {
    return new FirewallRule {
        Action = (FirewallRuleAction)rule.Action,
        ApplicationName = rule.ApplicationName,
        Description = rule.Description,
        // etc...
    };
}

Vb.Net(原创):

Public Shared Narrowing Operator CType(ByVal rule As INetFwRule) As FirewallRule

    Return New FirewallRule With {
        .Action = DirectCast(rule.Action, FirewallRuleAction),
        .ApplicationName = rule.ApplicationName,
        .Description = rule.Description,
        ' etc ...
    }

End Operator

但是,我在rule参数中收到此错误:

  

转换运算符无法从接口类型转换

有一种解决方法可以写CType

1 个答案:

答案 0 :(得分:3)

编译器禁止您定义将接口作为参数的转换运算符,因为它认为已经定义了这种转换(即内置的转换能力)。

您需要使用其他一些语法来启动INetFwRuleFirewallRule的转换 - 例如,INetFwRule的扩展名:

public static class NetFwRuleExt {
    public static FirewallRule ToFirewallRule(this INetFwRule rule) {
        return new FirewallRule {
            Action = (FirewallRuleAction)rule.Action,
            ApplicationName = rule.ApplicationName,
            Description = rule.Description,
            // etc...
        };
    }
}

而不是写

FirewallRule newRule = (FirewallRule)someRule;

您的API的客户端会写

FirewallRule newRule = someRule.ToFirewallRule();