首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何判断类型是否支持相等运算符

如何判断类型是否支持相等运算符
EN

Stack Overflow用户
提问于 2016-12-19 18:43:27
回答 1查看 154关注 0票数 5

我正在生成需要使用SyntaxGenerator检查相等性的代码

示例:

代码语言:javascript
复制
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)这样的东西

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

EN

回答 1

Stack Overflow用户

发布于 2016-12-19 20:59:04

正如Skeet建议的那样,我最终专攻了所有的东西:

代码语言:javascript
复制
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;
}

如果你发现了哑巴,请评论。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41220799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档