如何确定一个类型是否支持相等运算符

时间:2016-12-19 10:43:27

标签: c# roslyn

我使用SyntaxGenerator

生成需要检查相等性的代码

样品:

if (property.Type.IsValueType || property.Type == KnownSymbol.String)
{
    if (property.Type.TypeKind == TypeKind.Enum ||
        property.Type.GetMembers("op_Equality").Length == 1)
    {
        var valueEqualsExpression = syntaxGenerator.ValueEqualsExpression(
            SyntaxFactory.ParseName("value"),
            SyntaxFactory.ParseExpression(fieldAccess));
        return (IfStatementSyntax)syntaxGenerator.IfStatement(valueEqualsExpression, new[] { SyntaxFactory.ReturnStatement() });
    }
    ...

问题是这不能处理int等类型。

猜猜我正在寻找像SupportsValueEquals(ITypeSymbol symbol)

这样的东西

如何通过==确定类型是否支持相等?

1 个答案:

答案 0 :(得分:0)

正如Skeet建议我最终特别指出所有事情:

private static bool HasEqualityOperator(ITypeSymbol type)
{
    switch (type.SpecialType)
    {
        case SpecialType.System_Enum:
        case SpecialType.System_Boolean:
        case SpecialType.System_Char:
        case SpecialType.System_SByte:
        case SpecialType.System_Byte:
        case SpecialType.System_Int16:
        case SpecialType.System_UInt16:
        case SpecialType.System_Int32:
        case SpecialType.System_UInt32:
        case SpecialType.System_Int64:
        case SpecialType.System_UInt64:
        case SpecialType.System_Decimal:
        case SpecialType.System_Single:
        case SpecialType.System_Double:
        case SpecialType.System_String:
        case SpecialType.System_IntPtr:
        case SpecialType.System_UIntPtr:
        case SpecialType.System_DateTime:
            return true;
    }

    if (type.TypeKind == TypeKind.Enum)
    {
        return true;
    }

    foreach (var op in type.GetMembers("op_Equality"))
    {
        var opMethod = op as IMethodSymbol;
        if (opMethod?.Parameters.Length == 2 &&
            type.Equals(opMethod.Parameters[0].Type) &&
            type.Equals(opMethod.Parameters[1].Type))
        {
            return true;
        }
    }

    return false;
}

如果你发现愚蠢,请评论。