示例#1
0
        static ExpressionSyntax GetDefaultValueExpression(SemanticModel semanticModel, MethodStatementSyntax methodStatement, TypeSyntax type)
        {
            var typeSymbol = semanticModel.GetTypeInfo(type).Type;

            if (typeSymbol == null)
            {
                return(null);
            }

            if (typeSymbol.IsArrayType())
            {
                return(SyntaxFactory.ObjectCreationExpression(type));
            }

            if (typeSymbol.IsEnumType())
            {
                var members = type.GetMembers().OfType <EnumMemberDeclarationSyntax>();
                if (!members.Any())
                {
                    return(GetDefaultTypeExpression(type));
                }
                return(SyntaxFactory.MemberAccessExpression(
                           SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(members.First().Identifier)));
            }

            if (typeSymbol.IsKind(SymbolKind.DynamicType))
            {
                return(GetNothingExpression());
            }
            if (typeSymbol.IsReferenceType)
            {
                if (typeSymbol.GetTypeParameters().Any() && (methodStatement.TypeParameterList != null) && methodStatement.TypeParameterList.Parameters.Any())
                {
                    return(GetDefaultTypeExpression(type));
                }
                return(GetNothingExpression());
            }

            switch (typeSymbol.SpecialType)
            {
            case SpecialType.System_Boolean:
                return(SyntaxFactory.FalseLiteralExpression(SyntaxFactory.Token(SyntaxKind.FalseKeyword)));

            case SpecialType.System_Char:
                return(SyntaxFactory.LiteralExpression(SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal('\0')));

            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_Single:
            case SpecialType.System_Double:
            case SpecialType.System_Decimal:
                return(SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
            }
            if (typeSymbol.IsNullableType())
            {
                return(GetNothingExpression());
            }
            if (typeSymbol.IsValueType)
            {
                return(SyntaxFactory.ObjectCreationExpression(type));
            }

            return(GetDefaultTypeExpression(type));
        }