简体   繁体   中英

How to figure out if a type supports equality operator

I'm generating code that needs to check equality using SyntaxGenerator

Sample:

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() });
    }
    ...

Problem is that this does not handle types such as int .

Guess I'm looking for something like SupportsValueEquals(ITypeSymbol symbol)

How can I figure out if a type supports equality via == ?

As Skeet suggested I ended up specialcasing all the things:

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;
}

Please comment if you spot dumbs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM