当前位置: 首页>>代码示例>>C#>>正文


C# Type.IsNullable方法代码示例

本文整理汇总了C#中Type.IsNullable方法的典型用法代码示例。如果您正苦于以下问题:C# Type.IsNullable方法的具体用法?C# Type.IsNullable怎么用?C# Type.IsNullable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Type的用法示例。


在下文中一共展示了Type.IsNullable方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetDefaultMappingFromEnumType

        public static Type GetDefaultMappingFromEnumType(MappingSchema mappingSchema, Type enumType)
        {
            var type = enumType.ToNullableUnderlying();

            if (!type.IsEnumEx())
                return null;

            var fields =
            (
                from f in type.GetFieldsEx()
                where (f.Attributes & EnumField) == EnumField
                let attrs = mappingSchema.GetAttributes<MapValueAttribute>(f, a => a.Configuration)
                select
                (
                    from a in attrs
                    where a.Configuration == attrs[0].Configuration
                    orderby !a.IsDefault
                    select a
                ).ToList()
            ).ToList();

            Type defaultType = null;

            if (fields.All(attrs => attrs.Count != 0))
            {
                var attr = fields.FirstOrDefault(attrs => attrs[0].Value != null);

                if (attr != null)
                {
                    var valueType = attr[0].Value.GetType();

                    if (fields.All(attrs => attrs[0].Value == null || attrs[0].Value.GetType() == valueType))
                        defaultType = valueType;
                }
            }

            if (defaultType == null)
                defaultType = Enum.GetUnderlyingType(type);

            if (enumType.IsNullable() && !defaultType.IsClassEx() && !defaultType.IsNullable())
                defaultType = typeof(Nullable<>).MakeGenericType(defaultType);

            return defaultType;
        }
开发者ID:Convey-Compliance,项目名称:linq2db,代码行数:44,代码来源:ConvertBuilder.cs

示例2: GetConverter

        public static Tuple<LambdaExpression, LambdaExpression, bool> GetConverter(MappingSchema mappingSchema, Type from, Type to)
        {
            if (mappingSchema == null)
                mappingSchema = MappingSchema.Default;

            var p  = Expression.Parameter(from, "p");
            var ne = null as LambdaExpression;

            if (from == to)
                return Tuple.Create(Expression.Lambda(p, p), ne, false);

            if (to == typeof(object))
                return Tuple.Create(Expression.Lambda(Expression.Convert(p, typeof(object)), p), ne, false);

            var ex =
                GetConverter     (mappingSchema, p, @from, to) ??
                ConvertUnderlying(mappingSchema, p, @from, @from.ToNullableUnderlying(), to, to.ToNullableUnderlying()) ??
                ConvertUnderlying(mappingSchema, p, @from, @from.ToUnderlying(),         to, to.ToUnderlying());

            if (ex != null)
            {
                ne = Expression.Lambda(ex.Item1, p);

                if (from.IsNullable())
                    ex = Tuple.Create(
                        Expression.Condition(Expression.PropertyOrField(p, "HasValue"), ex.Item1, new DefaultValueExpression(mappingSchema, to)) as Expression,
                        ex.Item2);
                else if (from.IsClassEx())
                    ex = Tuple.Create(
                        Expression.Condition(Expression.NotEqual(p, Expression.Constant(null, from)), ex.Item1, new DefaultValueExpression(mappingSchema, to)) as Expression,
                        ex.Item2);
            }

            if (ex != null)
                return Tuple.Create(Expression.Lambda(ex.Item1, p), ne, ex.Item2);

            if (to.IsNullable())
            {
                var uto = to.ToNullableUnderlying();

                var defex = Expression.Call(_defaultConverter,
                    Expression.Convert(p, typeof(object)),
                    Expression.Constant(uto)) as Expression;

                if (defex.Type != uto)
                    defex = Expression.Convert(defex, uto);

                defex = GetCtor(uto, to, defex);

                return Tuple.Create(Expression.Lambda(defex, p), ne, false);
            }
            else
            {
                var defex = Expression.Call(_defaultConverter,
                    Expression.Convert(p, typeof(object)),
                    Expression.Constant(to)) as Expression;

                if (defex.Type != to)
                    defex = Expression.Convert(defex, to);

                return Tuple.Create(Expression.Lambda(defex, p), ne, false);
            }
        }
开发者ID:Convey-Compliance,项目名称:linq2db,代码行数:63,代码来源:ConvertBuilder.cs

示例3: GetToString

        static Expression GetToString(Type from, Type to, Expression p)
        {
            if (to == typeof(string) && !from.IsNullable())
            {
                var mi = from.GetMethodEx("ToString", new Type[0]);
                return mi != null ? Expression.Call(p, mi) : null;
            }

            return null;
        }
开发者ID:Convey-Compliance,项目名称:linq2db,代码行数:10,代码来源:ConvertBuilder.cs

示例4: ConvertTo

            internal static object ConvertTo(string valueString, Type type)
            {
                if (valueString == null)
                {
                    return null;
                }

                if (type.IsNullable() && String.Equals(valueString, "null", StringComparison.Ordinal))
                {
                    return null;
                }

                // TODO 1668: ODL beta1's ODataUriUtils.ConvertFromUriLiteral does not support converting uri literal
                // to ODataEnumValue, but beta1's ODataUriUtils.ConvertToUriLiteral supports converting ODataEnumValue
                // to uri literal.
                if (TypeHelper.IsEnum(type))
                {
                    string[] values = valueString.Split(new[] { '\'' }, StringSplitOptions.None);
                    if (values.Length == 3 && String.IsNullOrEmpty(values[2]))
                    {
                        // Remove the type name if the enum value is a fully qualified literal.
                        valueString = values[1];
                    }

                    Type enumType = TypeHelper.GetUnderlyingTypeOrSelf(type);
                    object[] parameters = new[] { valueString, Enum.ToObject(enumType, 0) };
                    bool isSuccessful = (bool)EnumTryParseMethod.MakeGenericMethod(enumType).Invoke(null, parameters);

                    if (!isSuccessful)
                    {
                        throw Error.InvalidOperation(SRResources.ModelBinderUtil_ValueCannotBeEnum, valueString, type.Name);
                    }

                    return parameters[1];
                }

                // The logic of "public static object ConvertFromUriLiteral(string value, ODataVersion version);" treats
                // the date value string (for example: 2015-01-02) as DateTimeOffset literal, and return a DateTimeOffset
                // object. However, the logic of
                // "object ConvertFromUriLiteral(string value, ODataVersion version, IEdmModel model, IEdmTypeReference typeReference);"
                // can return the correct Date object.
                if (type == typeof(Date) || type == typeof(Date?))
                {
                    EdmCoreModel model = EdmCoreModel.Instance;
                    IEdmPrimitiveTypeReference dateTypeReference = EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(type);
                    return ODataUriUtils.ConvertFromUriLiteral(valueString, ODataVersion.V4, model, dateTypeReference);
                }

                object value = ODataUriUtils.ConvertFromUriLiteral(valueString, ODataVersion.V4);

                bool isNonStandardEdmPrimitive;
                EdmLibHelpers.IsNonstandardEdmPrimitive(type, out isNonStandardEdmPrimitive);

                if (isNonStandardEdmPrimitive)
                {
                    return EdmPrimitiveHelpers.ConvertPrimitiveValue(value, type);
                }
                else
                {
                    type = Nullable.GetUnderlyingType(type) ?? type;
                    return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
                }
            }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:63,代码来源:ODataModelBinderProvider.cs

示例5: ConvertParameterType

		public override Type ConvertParameterType(Type type, DataType dataType)
		{
			if (type.IsNullable())
				type = type.ToUnderlying();

			switch (dataType)
			{
				case DataType.Boolean: if (type == typeof(bool)) return typeof(byte);   break;
				case DataType.Guid   : if (type == typeof(Guid)) return typeof(string); break;
			}

			return base.ConvertParameterType(type, dataType);
		}
开发者ID:Convey-Compliance,项目名称:linq2db,代码行数:13,代码来源:SapHanaOdbcDataProvider.cs

示例6: CanCreateEdmModel_WithDateAndTimeOfDay_AsActionParameter

        public void CanCreateEdmModel_WithDateAndTimeOfDay_AsActionParameter(Type paramType, string expect)
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock<ODataModelBuilder>();
            EntityTypeConfiguration<Movie> movie = builder.EntitySet<Movie>("Movies").EntityType;
            var actionBuilder = movie.Action("ActionName");
            actionBuilder.Parameter(paramType, "p1");

            MethodInfo method = typeof(ProcedureConfiguration).GetMethod("CollectionParameter", BindingFlags.Instance | BindingFlags.Public);
            method.MakeGenericMethod(paramType).Invoke(actionBuilder, new[] { "p2" });

            // Act
            IEdmModel model = builder.GetEdmModel();

            //Assert
            IEdmOperation action = Assert.Single(model.SchemaElements.OfType<IEdmAction>());
            Assert.Equal("ActionName", action.Name);

            IEdmOperationParameter parameter = action.FindParameter("p1");
            Assert.Equal(expect, parameter.Type.FullName());
            Assert.Equal(paramType.IsNullable(), parameter.Type.IsNullable);

            parameter = action.FindParameter("p2");
            Assert.Equal("Collection(" + expect + ")", parameter.Type.FullName());
            Assert.Equal(paramType.IsNullable(), parameter.Type.IsNullable);
        }
开发者ID:chinadragon0515,项目名称:WebApi,代码行数:26,代码来源:ActionConfigurationTest.cs

示例7: ConvertTo

            internal static object ConvertTo(string valueString, Type type)
            {
                if (valueString == null)
                {
                    return null;
                }

                // TODO 1668: ODL beta1's ODataUriUtils.ConvertFromUriLiteral does not support converting uri literal
                // to ODataEnumValue, but beta1's ODataUriUtils.ConvertToUriLiteral supports converting ODataEnumValue
                // to uri literal.
                if (TypeHelper.IsEnum(type))
                {
                    string[] values = valueString.Split(new[] { '\'' }, StringSplitOptions.None);
                    if (values.Length == 3 && String.IsNullOrEmpty(values[2]))
                    {
                        // Remove the type name if the enum value is a fully qualified literal.
                        valueString = values[1];
                    }

                    if (type.IsNullable() && String.Equals(valueString, "null", StringComparison.Ordinal))
                    {
                        return null;
                    }

                    Type enumType = TypeHelper.GetUnderlyingTypeOrSelf(type);
                    object[] parameters = new[] { valueString, Enum.ToObject(enumType, 0) };
                    bool isSuccessful = (bool)enumTryParseMethod.MakeGenericMethod(enumType).Invoke(null, parameters);

                    if (!isSuccessful)
                    {
                        throw Error.InvalidOperation(SRResources.ModelBinderUtil_ValueCannotBeEnum, valueString, type.Name);
                    }

                    return parameters[1];
                }

                object value = ODataUriUtils.ConvertFromUriLiteral(valueString, ODataVersion.V4);

                bool isNonStandardEdmPrimitive;
                EdmLibHelpers.IsNonstandardEdmPrimitive(type, out isNonStandardEdmPrimitive);

                if (isNonStandardEdmPrimitive)
                {
                    return EdmPrimitiveHelpers.ConvertPrimitiveValue(value, type);
                }
                else
                {
                    type = Nullable.GetUnderlyingType(type) ?? type;
                    return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
                }
            }
开发者ID:AndreGleichner,项目名称:aspnetwebstack,代码行数:51,代码来源:ODataModelBinderProvider.cs

示例8: NumericExpression

 public NumericExpression(Type type)
     : this()
 {
     IsNullable = type.IsNullable();
 }
开发者ID:dmitry-shechtman,项目名称:Orc.FilterBuilder,代码行数:5,代码来源:NumericExpression.cs

示例9: GetToString

        static Expression GetToString(Type from, Type to, Expression p)
        {
            if (to == typeof(string) && !from.IsNullable())
            {
                var mi = from.GetMethod("ToString", BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null);
                return mi != null ? Expression.Call(p, mi) : null;
            }

            return null;
        }
开发者ID:henleygao,项目名称:linq2db,代码行数:10,代码来源:ConvertBuilder.cs

示例10: GenerateNullableMethodCall

		// returns x=>x==null?null:f(x.Value) with cast to Nullable if needed
		private Maybe<Expression> GenerateNullableMethodCall(Type type, Expression instance, int errorPos, string id, TokenId nextToken, Lazy<Expression[]> argumentList)
		{
			
			if (type.IsNullable())
			{
				var expression = TryParseMemberAcces(type.GetGenericArguments()[0], Expression.Property(instance, "Value"), nextToken, errorPos, id);
				return expression.Select(e =>
				{
					return new
					{
						expression = e,
						protectedExpression = !e.Type.IsNullable() && e.Type.IsValueType
							? Expression.Convert(e, typeof (Nullable<>).MakeGenericType(e.Type))
							: e
					};
				}).Select( notNull =>
				{
					var condition = (Expression)Expression.Condition(Expression.Equal(instance, Expression.Constant(null, type)),
						Expression.Constant(null, notNull.protectedExpression.Type), notNull.protectedExpression);

					// attach raw expression to condition to get it name in GetConditionalName()
					ExtensionsProvider.SetValue(condition, notNull.expression);
					return condition;
				}
					).ToMaybe();
			}
			return Maybe.Nothing;
		}
开发者ID:chenhualei,项目名称:Target-Process-Plugins,代码行数:29,代码来源:ExpressionParser.cs


注:本文中的Type.IsNullable方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。