Here are the examples of the csharp api System.Nullable.GetUnderlyingType(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1137 Examples
19
Source : LightDataTableShared.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
internal static object ValueByType(Type propertyType, object defaultValue = null)
{
if (defaultValue != null)
{
var typeOne = propertyType;
var typeTwo = defaultValue.GetType();
if (Nullable.GetUnderlyingType(typeOne) != null)
typeOne = Nullable.GetUnderlyingType(typeOne);
if (Nullable.GetUnderlyingType(typeTwo) != null)
typeTwo = Nullable.GetUnderlyingType(typeTwo);
if (typeOne == typeTwo)
return defaultValue;
}
if (propertyType.IsEnum)
return Activator.CreateInstance(propertyType);
if (propertyType == typeof(int?))
return new int?();
if (propertyType == typeof(int))
return 0;
if (propertyType == typeof(long?))
return new long?();
if (propertyType == typeof(long))
return 0;
if (propertyType == typeof(float?))
return new long?();
if (propertyType == typeof(float))
return 0;
if (propertyType == typeof(decimal?))
return new decimal?();
if (propertyType == typeof(decimal))
return new decimal();
if (propertyType == typeof(double?))
return new double?();
if (propertyType == typeof(double))
return new double();
if (propertyType == typeof(DateTime?))
return new DateTime?();
if (propertyType == typeof(DateTime))
return SqlDateTime.MinValue.Value;
if (propertyType == typeof(bool?))
return new bool?();
if (propertyType == typeof(bool))
return false;
if (propertyType == typeof(TimeSpan?))
return new TimeSpan?();
if (propertyType == typeof(TimeSpan))
return new TimeSpan();
if (propertyType == typeof(Guid?))
return new Guid?();
if (propertyType == typeof(Guid))
return new Guid();
if (propertyType == typeof(byte))
return new byte();
if (propertyType == typeof(byte?))
return new byte?();
if (propertyType == typeof(byte[]))
return new byte[0];
return propertyType == typeof(string) ? string.Empty : null;
}
19
Source : EnumBindingSourceExtension.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (this.enumType == null)
{
throw new InvalidOperationException("The EnumType must be specified.");
}
Type actualEnumType = Nullable.GetUnderlyingType(this.enumType) ?? this.enumType;
Array enumValues = Enum.GetValues(actualEnumType);
if (actualEnumType == this.enumType)
{
return enumValues;
}
Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
19
Source : OpenEdgeSharedTypeExtensions.cs
with Apache License 2.0
from alexwiese
with Apache License 2.0
from alexwiese
public static Type UnwrapNullableType(this Type type) => Nullable.GetUnderlyingType(type) ?? type;
19
Source : Reflection.cs
with MIT License
from alfa-laboratory
with MIT License
from alfa-laboratory
public static Type GetObjectType(this object obj, bool checkElementType = false)
{
Type t;
switch(obj)
{
case null:
return null;
case Type type:
t = type;
break;
case ParameterInfo info:
t = info.ParameterType;
break;
case PropertyInfo info:
t = info.PropertyType;
break;
case FieldInfo info:
t = info.FieldType;
break;
default:
t = obj.GetType();
break;
}
if(checkElementType && t.HasElementType)
{
t = t.GetElementType();
}
t = Nullable.GetUnderlyingType(t) ?? t;
return t;
}
19
Source : OpenApiSchemaExtensions.cs
with MIT License
from aliencube
with MIT License
from aliencube
[Obsolete("This method is now obsolete", error: true)]
public static Dictionary<string, OpenApiSchema> ToOpenApiSchemas(this Type type, NamingStrategy namingStrategy, OpenApiSchemaVisibilityAttribute attribute = null, bool returnSingleSchema = false, int depth = 0)
{
type.ThrowIfNullOrDefault();
var schema = (OpenApiSchema)null;
var schemeName = type.GetOpenApiTypeName(namingStrategy);
if (depth == 8)
{
schema = new OpenApiSchema()
{
Type = type.ToDataType(),
Format = type.ToDataFormat()
};
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
depth++;
if (type.IsJObjectType())
{
schema = typeof(object).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiNullable(out var unwrappedValueType))
{
schema = unwrappedValueType.ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
schema.Nullable = true;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
schema = new OpenApiSchema()
{
Type = type.ToDataType(),
Format = type.ToDataFormat()
};
if (!attribute.IsNullOrDefault())
{
var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());
schema.Extensions.Add("x-ms-visibility", visibility);
}
if (type.IsUnflaggedEnumType())
{
var converterAttribute = type.GetCustomAttribute<JsonConverterAttribute>();
if (!converterAttribute.IsNullOrDefault()
&& typeof(StringEnumConverter).IsreplacedignableFrom(converterAttribute.ConverterType))
{
var enums = type.ToOpenApiStringCollection(namingStrategy);
schema.Type = "string";
schema.Format = null;
schema.Enum = enums;
schema.Default = enums.First();
}
else
{
var enums = type.ToOpenApiIntegerCollection();
schema.Enum = enums;
schema.Default = enums.First();
}
}
if (type.IsSimpleType())
{
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiDictionary())
{
schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiArray())
{
schema.Type = "array";
schema.Items = (type.GetElementType() ?? type.GetGenericArguments()[0]).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
var allProperties = type.IsInterface
? new[] { type }.Concat(type.GetInterfaces()).SelectMany(i => i.GetProperties())
: type.GetProperties();
var properties = allProperties.Where(p => !p.ExistsCustomAttribute<JsonIgnoreAttribute>());
var retVal = new Dictionary<string, OpenApiSchema>();
foreach (var property in properties)
{
var visiblity = property.GetCustomAttribute<OpenApiSchemaVisibilityAttribute>(inherit: false);
var propertyName = property.GetJsonPropertyName(namingStrategy);
var ts = property.DeclaringType.GetGenericArguments();
if (!ts.Any())
{
if (property.PropertyType.IsUnflaggedEnumType() && !returnSingleSchema)
{
var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var enumReference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiReferenceId(false, false)
};
var schema1 = new OpenApiSchema() { Reference = enumReference };
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
}
else if (property.PropertyType.IsSimpleType() || Nullable.GetUnderlyingType(property.PropertyType) != null || returnSingleSchema)
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else if (property.PropertyType.IsOpenApiDictionary())
{
var elementType = property.PropertyType.GetGenericArguments()[1];
if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else
{
var recur1 = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var elementReference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = elementType.GetOpenApiReferenceId(false, false)
};
var dictionarySchema = new OpenApiSchema()
{
Type = "object",
AdditionalProperties = new OpenApiSchema() { Reference = elementReference }
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
}
}
else if (property.PropertyType.IsOpenApiArray())
{
var elementType = property.PropertyType.GetElementType() ?? property.PropertyType.GetGenericArguments()[0];
if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else
{
var elementReference = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(elementReference);
var reference1 = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = elementType.GetOpenApiReferenceId(false, false)
};
var arraySchema = new OpenApiSchema()
{
Type = "array",
Items = new OpenApiSchema()
{
Reference = reference1
}
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
}
}
else
{
var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var reference1 = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiReferenceId(false, false)
};
var schema1 = new OpenApiSchema() { Reference = reference1 };
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
}
continue;
}
var reference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiRootReferenceId()
};
var referenceSchema = new OpenApiSchema() { Reference = reference };
if (!ts.Contains(property.PropertyType))
{
if (property.PropertyType.IsOpenApiDictionary())
{
reference.Id = property.PropertyType.GetOpenApiReferenceId(true, false);
var dictionarySchema = new OpenApiSchema()
{
Type = "object",
AdditionalProperties = referenceSchema
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
continue;
}
if (property.PropertyType.IsOpenApiArray())
{
reference.Id = property.PropertyType.GetOpenApiReferenceId(false, true);
var arraySchema = new OpenApiSchema()
{
Type = "array",
Items = referenceSchema
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
continue;
}
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
continue;
}
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = referenceSchema;
}
retVal[schemeName] = schema;
return retVal;
}
19
Source : TypeExtensions.cs
with MIT License
from aliencube
with MIT License
from aliencube
private static bool IsNullableType(this Type type, out Type underlyingType)
{
underlyingType = Nullable.GetUnderlyingType(type);
return !underlyingType.IsNullOrDefault();
}
19
Source : SyntaxTreeToQueryConvertor.cs
with MIT License
from alirezanet
with MIT License
from alirezanet
private static LambdaExpression? GenerateExpression(
Expression body,
ParameterExpression parameter,
ValueExpressionSyntax valueExpression,
SyntaxNode op,
bool allowNullSearch,
Func<string, object>? convertor)
{
// Remove the boxing for value types
if (body.NodeType == ExpressionType.Convert) body = ((UnaryExpression)body).Operand;
object? value = valueExpression.ValueToken.Text;
// execute user custom Convertor
if (convertor != null)
value = convertor.Invoke(valueExpression.ValueToken.Text) ?? null;
// handle the `null` keyword in value
if (allowNullSearch && op.Kind is SyntaxKind.Equal or SyntaxKind.NotEqual && value?.ToString() == "null")
value = null;
// type fixer
if (value is not null && body.Type != value.GetType())
{
try
{
// handle broken guids, github issue #2
if (body.Type == typeof(Guid) && !Guid.TryParse(value!.ToString(), out _)) value = Guid.NewGuid().ToString();
var converter = TypeDescriptor.GetConverter(body.Type);
value = converter.ConvertFromString(value!.ToString())!;
}
catch (FormatException)
{
// return no records in case of any exception in formatting
return Expression.Lambda(Expression.Constant(false), parameter); // q => false
}
}
// handle case-Insensitive search
if (value is not null && valueExpression.IsCaseInsensitive
&& op.Kind is not SyntaxKind.GreaterThan
&& op.Kind is not SyntaxKind.LessThan
&& op.Kind is not SyntaxKind.GreaterOrEqualThan
&& op.Kind is not SyntaxKind.LessOrEqualThan)
{
value = value.ToString().ToLower();
body = Expression.Call(body, GetToLowerMethod());
}
Expression be;
// use string.Compare instead of operators if value and field are both strings
var areBothStrings = body.Type == typeof(string) && value?.GetType() == typeof(string);
switch (op.Kind)
{
case SyntaxKind.Equal when !valueExpression.IsNullOrDefault:
be = Expression.Equal(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.Equal when valueExpression.IsNullOrDefault:
if (body.Type == typeof(string))
be = Expression.Call(null, GetIsNullOrEmptyMethod(), body);
else
{
var canBeNull = !body.Type.IsValueType || (Nullable.GetUnderlyingType(body.Type) != null);
be = canBeNull
? Expression.OrElse(Expression.Equal(body, Expression.Constant(null)), Expression.Equal(body, Expression.Default(body.Type)))
: Expression.Equal(body, Expression.Default(body.Type));
}
break;
case SyntaxKind.NotEqual when !valueExpression.IsNullOrDefault:
be = Expression.NotEqual(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.NotEqual when valueExpression.IsNullOrDefault:
if (body.Type == typeof(string))
be = Expression.Not(Expression.Call(null, GetIsNullOrEmptyMethod(), body));
else
{
var canBeNull = !body.Type.IsValueType || (Nullable.GetUnderlyingType(body.Type) != null);
be = canBeNull
? Expression.AndAlso(Expression.NotEqual(body, Expression.Constant(null)),
Expression.NotEqual(body, Expression.Default(body.Type)))
: Expression.NotEqual(body, Expression.Default(body.Type));
}
break;
case SyntaxKind.GreaterThan when areBothStrings == false:
be = Expression.GreaterThan(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.LessThan when areBothStrings == false:
be = Expression.LessThan(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.GreaterOrEqualThan when areBothStrings == false:
be = Expression.GreaterThanOrEqual(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.LessOrEqualThan when areBothStrings == false:
be = Expression.LessThanOrEqual(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.GreaterThan when areBothStrings:
be = GetGreaterThanExpression(body, valueExpression, value);
break;
case SyntaxKind.LessThan when areBothStrings:
be = GetLessThanExpression(body, valueExpression, value);
break;
case SyntaxKind.GreaterOrEqualThan when areBothStrings:
be = GetGreaterThanOrEqualExpression(body, valueExpression, value);
break;
case SyntaxKind.LessOrEqualThan when areBothStrings:
be = GetLessThanOrEqualExpression(body, valueExpression, value);
break;
case SyntaxKind.Like:
be = Expression.Call(body, GetContainsMethod(), GetValueExpression(body.Type, value));
break;
case SyntaxKind.NotLike:
be = Expression.Not(Expression.Call(body, GetContainsMethod(), GetValueExpression(body.Type, value)));
break;
case SyntaxKind.StartsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value?.ToString()));
}
else
be = Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value));
break;
case SyntaxKind.EndsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value?.ToString()));
}
else
be = Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value));
break;
case SyntaxKind.NotStartsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Not(Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value?.ToString())));
}
else
be = Expression.Not(Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value)));
break;
case SyntaxKind.NotEndsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Not(Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value?.ToString())));
}
else
be = Expression.Not(Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value)));
break;
default:
return null;
}
return Expression.Lambda(be, parameter);
}
19
Source : DynamoDbContextMetadata.cs
with MIT License
from AllocZero
with MIT License
from AllocZero
private DdbConverter GetOrAddCachedConverter(Type propertyType, Type? converterType)
{
converterType ??= propertyType.GetCustomAttribute<DynamoDbConverterAttribute>(true)?.ConverterType;
DdbConverter? converter = null;
if (converterType != null)
{
converter = GetOrAddKnownConverter(propertyType, converterType);
}
else
{
converter = FindConverter(_converters, this, propertyType);
converter ??= FindConverter(InternalConverters, this, propertyType);
converter ??= DefaultDdbConverterFactory.CreateFromType(propertyType);
// Check nested object converter in the end to make sure it does not override other converters
if (converter == null && propertyType.IsClreplaced)
converter = GetOrAddNestedObjectConverter(propertyType);
if (converter == null)
throw new DdbException($"Type '{propertyType.Name}' requires an explicit ddb converter.");
}
if (!propertyType.IsValueType)
return converter;
var type = Nullable.GetUnderlyingType(propertyType);
if (type is null)
return converter;
if (converter.Type == propertyType)
return converter;
var nullableConverterType = typeof(NullableValueTypeDdbConverter<>).MakeGenericType(type);
return (DdbConverter) Activator.CreateInstance(nullableConverterType, converter);
}
19
Source : BufferHelpers.cs
with MIT License
from allisterb
with MIT License
from allisterb
private static bool IsReferenceOrContainsReferencesCore(Type type)
{
if (type.GetTypeInfo().IsPrimitive) // This is hopefully the common case. All types that return true for this are value types w/out embedded references.
return false;
if (!type.GetTypeInfo().IsValueType)
return true;
// If type is a Nullable<> of something, unwrap it first.
Type underlyingNullable = Nullable.GetUnderlyingType(type);
if (underlyingNullable != null)
type = underlyingNullable;
if (type.GetTypeInfo().IsEnum)
return false;
foreach (FieldInfo field in type.GetTypeInfo().DeclaredFields)
{
if (field.IsStatic)
continue;
if (IsReferenceOrContainsReferencesCore(field.FieldType))
return true;
}
return false;
}
19
Source : BufferHelpers.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static bool IsReferenceOrContainsReferences(Type type, out FieldInfo referenceField)
{
referenceField = null;
if (type.GetTypeInfo().IsPrimitive) // This is hopefully the common case. All types that return true for this are value types w/out embedded references.
return false;
if (!type.GetTypeInfo().IsValueType)
return true;
// If type is a Nullable<> of something, unwrap it first.
Type underlyingNullable = Nullable.GetUnderlyingType(type);
if (underlyingNullable != null)
type = underlyingNullable;
if (type.GetTypeInfo().IsEnum)
return false;
foreach (FieldInfo field in type.GetTypeInfo().DeclaredFields)
{
if (field.IsStatic)
continue;
if (IsReferenceOrContainsReferences(field.FieldType, out referenceField))
{
referenceField = field;
return true;
}
}
return false;
}
19
Source : DefaultDdbConverterFactory.cs
with MIT License
from AllocZero
with MIT License
from AllocZero
public static DdbConverter? CreateFromType(Type sourceType)
{
return ConvertersFromTypeCache.GetOrAdd(sourceType, st =>
{
var type = Nullable.GetUnderlyingType(st) ?? st;
// TODO: Add DateTimeOffset converters
var converter = type switch
{
_ when type == typeof(string) => Create<StringDdbConverter>(),
_ when type == typeof(DateTime) => ConvertersCache.GetOrAdd(typeof(DateTime),
x => new DateTimeDdbConverter("O", 28) {DateTimeStyles = DateTimeStyles.RoundtripKind}),
_ when type == typeof(int) => Create<IntDdbConverter>(),
_ when type == typeof(double) => Create<DoubleDdbConverter>(),
_ when type == typeof(long) => Create<LongDdbConverter>(),
_ when type == typeof(decimal) => Create<DecimalDdbConverter>(),
_ when type == typeof(bool) => Create<BoolDdbConverter>(),
_ when type == typeof(Guid) => Create<GuidDdbConverter>(),
_ when type.IsEnum => CreateEnumConverter(type),
_ when type == typeof(byte) => Create<ByteDdbConverter>(),
_ when type == typeof(short) => Create<ShortDdbConverter>(),
_ when type == typeof(ushort) => Create<UShortDdbConverter>(),
_ when type == typeof(uint) => Create<UIntDdbConverter>(),
_ when type == typeof(ulong) => Create<ULongDdbConverter>(),
_ when type == typeof(float) => Create<FloatDdbConverter>(),
_ when type == typeof(byte[]) => Create<BinaryDdbConverter>(),
_ when type == typeof(List<byte[]>) => Create<ListBinarySetDdbConverter>(),
_ when type == typeof(IList<byte[]>) => Create<IListBinarySetDdbConverter>(),
_ => null
};
return converter;
}
19
Source : TypeExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static Type Unwrap([NotNull] this Type type)
=> Nullable.GetUnderlyingType(type) ?? type;
19
Source : TypeExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static Type GetUnderlyingType([NotNull] this Type type)
=> Nullable.GetUnderlyingType(type);
19
Source : TypeExtensions.cs
with MIT License
from amolines
with MIT License
from amolines
public static bool IsSimpleOrNullableType(this Type type)
{
if (type.IsNullableType())
{
type = Nullable.GetUnderlyingType(type);
}
return IsSimpleType(type);
}
19
Source : EnumBindingSourceExtension.cs
with GNU General Public License v3.0
from androllen
with GNU General Public License v3.0
from androllen
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (null == this._enumType)
throw new InvalidOperationException("The EnumType must be specified.");
Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
Array enumValues = Enum.GetValues(actualEnumType);
if (actualEnumType == this._enumType)
return enumValues;
Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
19
Source : ModelDescriptionGenerator.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDoreplacedentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsreplacedignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsreplacedignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsreplacedignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsreplacedignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsreplacedignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
19
Source : SqlMapper.Async.cs
with MIT License
from anet-team
with MIT License
from anet-team
internal static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, Type effectiveType, CommandDefinition command)
{
object param = command.Parameters;
var idenreplacedy = new Idenreplacedy(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType(), null);
var info = GetCacheInfo(idenreplacedy, param, command.AddToCache);
bool wasClosed = cnn.State == ConnectionState.Closed;
var cancel = command.CancellationToken;
using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader))
{
DbDataReader reader = null;
try
{
if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false);
reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, cancel).ConfigureAwait(false);
var tuple = info.Deserializer;
int hash = GetColumnHash(reader);
if (tuple.Func == null || tuple.Hash != hash)
{
if (reader.FieldCount == 0)
return Enumerable.Empty<T>();
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));
if (command.AddToCache) SetQueryCache(idenreplacedy, info);
}
var func = tuple.Func;
if (command.Buffered)
{
var buffer = new List<T>();
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
while (await reader.ReadAsync(cancel).ConfigureAwait(false))
{
object val = func(reader);
if (val == null || val is T)
{
buffer.Add((T)val);
}
else
{
buffer.Add((T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture));
}
}
while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore subsequent result sets */ }
command.OnCompleted();
return buffer;
}
else
{
// can't use ReadAsync / cancellation; but this will have to do
wasClosed = false; // don't close if handing back an open reader; rely on the command-behavior
var deferred = ExecuteReaderSync<T>(reader, func, command.Parameters);
reader = null; // to prevent it being disposed before the caller gets to see it
return deferred;
}
}
finally
{
using (reader) { /* dispose if non-null */ }
if (wasClosed) cnn.Close();
}
}
}
19
Source : SqlMapper.Async.cs
with MIT License
from anet-team
with MIT License
from anet-team
internal static async Task<T> QueryRowAsync<T>(this IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command)
{
object param = command.Parameters;
var idenreplacedy = new Idenreplacedy(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType(), null);
var info = GetCacheInfo(idenreplacedy, param, command.AddToCache);
bool wasClosed = cnn.State == ConnectionState.Closed;
var cancel = command.CancellationToken;
using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader))
{
DbDataReader reader = null;
try
{
if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false);
reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, (row & Row.Single) != 0
? CommandBehavior.SequentialAccess | CommandBehavior.SingleResult // need to allow multiple rows, to check fail condition
: CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow, cancel).ConfigureAwait(false);
T result = default(T);
if (await reader.ReadAsync(cancel).ConfigureAwait(false) && reader.FieldCount != 0)
{
var tuple = info.Deserializer;
int hash = GetColumnHash(reader);
if (tuple.Func == null || tuple.Hash != hash)
{
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));
if (command.AddToCache) SetQueryCache(idenreplacedy, info);
}
var func = tuple.Func;
object val = func(reader);
if (val == null || val is T)
{
result = (T)val;
}
else
{
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
result = (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
}
if ((row & Row.Single) != 0 && await reader.ReadAsync(cancel).ConfigureAwait(false)) ThrowMultipleRows(row);
while (await reader.ReadAsync(cancel).ConfigureAwait(false)) { /* ignore rows after the first */ }
}
else if ((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one
{
ThrowZeroRows(row);
}
while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore result sets after the first */ }
return result;
}
finally
{
using (reader) { /* dispose if non-null */ }
if (wasClosed) cnn.Close();
}
}
}
19
Source : DefaultTypeMap.cs
with MIT License
from anet-team
with MIT License
from anet-team
public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
var constructors = _type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (ConstructorInfo ctor in constructors.OrderBy(c => c.IsPublic ? 0 : (c.IsPrivate ? 2 : 1)).ThenBy(c => c.GetParameters().Length))
{
ParameterInfo[] ctorParameters = ctor.GetParameters();
if (ctorParameters.Length == 0)
return ctor;
if (ctorParameters.Length != types.Length)
continue;
int i = 0;
for (; i < ctorParameters.Length; i++)
{
if (!string.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase))
break;
if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary)
continue;
var unboxedType = Nullable.GetUnderlyingType(ctorParameters[i].ParameterType) ?? ctorParameters[i].ParameterType;
if ((unboxedType != types[i] && !SqlMapper.HasTypeHandler(unboxedType))
&& !(unboxedType.IsEnum() && Enum.GetUnderlyingType(unboxedType) == types[i])
&& !(unboxedType == typeof(char) && types[i] == typeof(string))
&& !(unboxedType.IsEnum() && types[i] == typeof(string)))
{
break;
}
}
if (i == ctorParameters.Length)
return ctor;
}
return null;
}
19
Source : SqlMapper.GridReader.cs
with MIT License
from anet-team
with MIT License
from anet-team
private T ReadRow<T>(Type type, Row row)
{
if (reader == null) throw new ObjectDisposedException(GetType().FullName, "The reader has been disposed; this can happen after all data has been consumed");
if (IsConsumed) throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once");
IsConsumed = true;
T result = default(T);
if (reader.Read() && reader.FieldCount != 0)
{
var typedIdenreplacedy = idenreplacedy.ForGrid(type, gridIndex);
CacheInfo cache = GetCacheInfo(typedIdenreplacedy, null, addToCache);
var deserializer = cache.Deserializer;
int hash = GetColumnHash(reader);
if (deserializer.Func == null || deserializer.Hash != hash)
{
deserializer = new DeserializerState(hash, GetDeserializer(type, reader, 0, -1, false));
cache.Deserializer = deserializer;
}
object val = deserializer.Func(reader);
if (val == null || val is T)
{
result = (T)val;
}
else
{
var convertToType = Nullable.GetUnderlyingType(type) ?? type;
result = (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
}
if ((row & Row.Single) != 0 && reader.Read()) ThrowMultipleRows(row);
while (reader.Read()) { /* ignore subsequent rows */ }
}
else if ((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one
{
ThrowZeroRows(row);
}
NextResult();
return result;
}
19
Source : SqlMapper.GridReader.cs
with MIT License
from anet-team
with MIT License
from anet-team
private IEnumerable<T> ReadDeferred<T>(int index, Func<IDataReader, object> deserializer, Type effectiveType)
{
try
{
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
while (index == gridIndex && reader.Read())
{
object val = deserializer(reader);
if (val == null || val is T)
{
yield return (T)val;
}
else
{
yield return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
}
}
}
finally // finally so that First etc progresses things even when multiple rows
{
if (index == gridIndex)
{
NextResult();
}
}
}
19
Source : SqlMapper.IDataReader.cs
with MIT License
from anet-team
with MIT License
from anet-team
public static IEnumerable<T> Parse<T>(this IDataReader reader)
{
if (reader.Read())
{
var effectiveType = typeof(T);
var deser = GetDeserializer(effectiveType, reader, 0, -1, false);
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
do
{
object val = deser(reader);
if (val == null || val is T)
{
yield return (T)val;
}
else
{
yield return (T)Convert.ChangeType(val, convertToType, System.Globalization.CultureInfo.InvariantCulture);
}
} while (reader.Read());
}
}
19
Source : JsonMapper.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
private static object ReadValue(Type inst_type, JsonReader reader)
{
reader.Read();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null)
{
#if NETSTANDARD1_5
if (inst_type.IsClreplaced() || underlying_type != null) {
return null;
}
#else
if (inst_type.IsClreplaced || underlying_type != null)
{
return null;
}
#endif
throw new JsonException(String.Format("Can't replacedign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean)
{
Type json_type = reader.Value.GetType();
if (value_type.IsreplacedignableFrom(json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey(json_type) &&
custom_importers_table[json_type].ContainsKey(value_type))
{
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer(reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey(json_type) &&
base_importers_table[json_type].ContainsKey(value_type))
{
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer(reader.Value);
}
// Maybe it's an enum
#if NETSTANDARD1_5
if (value_type.IsEnum())
return Enum.ToObject (value_type, reader.Value);
#else
if (value_type.IsEnum)
return Enum.ToObject(value_type, reader.Value);
#endif
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp(value_type, json_type);
if (conv_op != null)
return conv_op.Invoke(null,
new object[] { reader.Value });
// No luck
throw new JsonException(String.Format("Can't replacedign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart)
{
AddArrayMetadata(inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (!t_data.IsArray && !t_data.IsList)
throw new JsonException(String.Format("Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (!t_data.IsArray)
{
list = (IList) Activator.CreateInstance(inst_type);
elem_type = t_data.ElementType;
}
else
{
list = new ArrayList();
elem_type = inst_type.GetElementType();
}
while (true)
{
object item = ReadValue(elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add(item);
}
if (t_data.IsArray)
{
int n = list.Count;
instance = Array.CreateInstance(elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue(list[i], i);
}
else
instance = list;
}
else if (reader.Token == JsonToken.ObjectStart)
{
AddObjectMetadata(value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance(value_type);
while (true)
{
reader.Read();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey(property))
{
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField)
{
((FieldInfo) prop_data.Info).SetValue(instance, ReadValue(prop_data.Type, reader));
}
else
{
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue(instance,
ReadValue(prop_data.Type, reader),
null);
else
ReadValue(prop_data.Type, reader);
}
}
else
{
if (!t_data.IsDictionary)
{
if (!reader.SkipNonMembers)
{
throw new JsonException(String.Format("The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
}
ReadSkip(reader);
continue;
}
var dicTypes = instance.GetType().GetGenericArguments();
var converter = System.ComponentModel.TypeDescriptor.GetConverter(dicTypes[0]);
object key = property;
if (converter != null)
{
key = converter.ConvertFromString(property);
t_data.ElementType = dicTypes[1];
}
((IDictionary) instance).Add(key, ReadValue(t_data.ElementType, reader));
}
}
}
return instance;
}
19
Source : Helpers.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
internal static Type GetUnderlyingType(Type type)
{
return Nullable.GetUnderlyingType(type);
}
19
Source : TimelineModel.DefaultValues.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private void SetDefaultValues()
{
var defaults = this.Defaults.Union(GetSuperDefaultValues())
.Where(x => (x.Enabled ?? true));
this.Walk((element) =>
{
inheritsElement(element);
setDefaultValuesToElement(element);
return false;
});
void setDefaultValuesToElement(TimelineBase element)
{
try
{
foreach (var def in defaults
.Where(x => x.TargetElement == element.TimelineType))
{
var pi = GetPropertyInfo(element, def.TargetAttribute);
if (pi == null)
{
continue;
}
var value = pi.GetValue(element);
if (value == null)
{
object defValue = null;
if (def.Value != null)
{
var type = pi.PropertyType;
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
type = Nullable.GetUnderlyingType(type);
}
if (!type.IsEnum)
{
defValue = Convert.ChangeType(def.Value, type);
}
else
{
defValue = Enum.Parse(type, def.Value, true);
}
}
if (defValue != null)
{
pi.SetValue(element, defValue);
}
}
}
}
catch (Exception ex)
{
Logger.Write($"{TimelineConstants.LogSymbol} Load default values error.", ex);
}
}
void inheritsElement(TimelineBase element)
{
if (string.IsNullOrEmpty(element.Inherits))
{
return;
}
var super = default(TimelineBase);
this.Walk(x =>
{
if (x.Enabled.GetValueOrDefault() &&
x.TimelineType == element.TimelineType &&
!string.IsNullOrEmpty(x.Name) &&
string.Equals(x.Name, element.Inherits, StringComparison.OrdinalIgnoreCase))
{
super = x;
return true;
}
return false;
});
if (super == null)
{
return;
}
var properties = super.GetType().GetProperties(
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic);
foreach (var pi in properties)
{
var superValue = pi.GetValue(super);
if (superValue == null)
{
continue;
}
var targetValue = pi.GetValue(element);
if (targetValue == null)
{
pi.SetValue(element, superValue);
}
}
}
}
19
Source : LiteralExpression.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public bool TryGetValue(Type converType, out object value)
{
Type nullableArg = Nullable.GetUnderlyingType(converType);
if (nullableArg != null)
{
return _TryGetValue(nullableArg, out value);
}
return _TryGetValue(converType, out value);
}
19
Source : CybtansModelBinder.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private static void SetValue(ModelBindingContext bindingContext, object obj, string value, string property)
{
if (obj is IReflectorMetadataProvider reflectorMetadata)
{
var accesor = reflectorMetadata.GetAccesor();
var propCode = accesor.GetPropertyCode(Pascal(property));
var propType = accesor.GetPropertyType(propCode);
propType = Nullable.GetUnderlyingType(propType) ?? propType;
reflectorMetadata.SetValue(Pascal(property),
propType != typeof(string) ?
Convert.ChangeType(value, propType) :
value);
}
else
{
var prop = bindingContext.ModelMetadata.Properties.FirstOrDefault(x => x.Name.ToUpperInvariant() == property.ToUpperInvariant());
prop?.PropertySetter(obj,
prop.ModelType != typeof(string) ?
Convert.ChangeType(value, prop.UnderlyingOrModelType) :
value);
}
}
19
Source : CybtansModelBinder.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private static void SetValue(ModelBindingContext bindingContext, object obj, object value, string property)
{
if (obj is IReflectorMetadataProvider reflectorMetadata)
{
var accesor = reflectorMetadata.GetAccesor();
var propCode = accesor.GetPropertyCode(Pascal(property));
var propType = accesor.GetPropertyType(propCode);
propType = Nullable.GetUnderlyingType(propType) ?? propType;
reflectorMetadata.SetValue(Pascal(property), value);
}
else
{
var prop = bindingContext.ModelMetadata.Properties.FirstOrDefault(x => x.Name.ToUpperInvariant() == property.ToUpperInvariant());
prop?.PropertySetter(obj, value);
}
}
19
Source : BinarySerializer.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public unsafe void Serialize(Stream stream, object obj)
{
if (obj == null)
{
stream.WriteByte((byte)Types.TYPE_NONE);
return;
}
var type = obj.GetType();
type = Nullable.GetUnderlyingType(type) ?? type;
switch (obj)
{
case bool boolValue:
stream.WriteByte(boolValue ? (byte)Types.TYPE_TRUE : (byte)Types.TYPE_FALSE);
break;
case byte byteV:
WriteInteger(stream, byteV);
break;
case sbyte sByteV:
WriteInteger(stream, sByteV);
break;
case short shortV:
WriteInteger(stream, shortV);
break;
case ushort ushortV:
WriteInteger(stream, ushortV);
break;
case int intV:
WriteInteger(stream, intV);
break;
case uint uintV:
WriteInteger(stream, uintV);
break;
case long longV:
WriteInteger(stream, longV);
break;
case ulong ulongV:
WriteInteger(stream, ulongV);
break;
case decimal decV:
WriteDecimal(stream, decV);
break;
case float floatV:
WriteFloat(stream, floatV);
break;
case double doubleV:
WriteDouble(stream, doubleV);
break;
case char ch:
WriteChar(stream, ch);
break;
case string str:
WriteString(stream, str);
break;
case byte[] bytes:
WriteLenght(stream, bytes.Length, Types.TYPE_BINARY_8, Types.TYPE_BINARY_16, Types.TYPE_BINARY_32);
stream.Write(bytes, 0, bytes.Length);
break;
case DateTime dateTime:
stream.WriteByte((byte)Types.TYPE_DATETIME);
TimeSpan span = dateTime - EPOCH;
WriteNumber(span.Ticks, stream);
break;
case Guid guid:
WriteGuid(stream, guid);
break;
case Array array:
WriteLenght(stream, array.Length, Types.TYPE_ARRAY_8, Types.TYPE_ARRAY_16, Types.TYPE_ARRAY_32);
WriteArray(stream, array);
break;
case ICollection collection:
if (collection is IDictionary dict)
{
WriteLenght(stream, dict.Count, Types.TYPE_MAP_8, Types.TYPE_MAP_16, Types.TYPE_MAP_32);
WriteMap(stream, dict);
}
else if(collection is IList list)
{
WriteLenght(stream, list.Count, Types.TYPE_LIST_8, Types.TYPE_LIST_16, Types.TYPE_LIST_32);
WriteList(stream, list);
}
else
{
WriteLenght(stream, collection.Count, Types.TYPE_LIST_8, Types.TYPE_LIST_16, Types.TYPE_LIST_32);
WriteEnumerable(stream, collection);
}
break;
case IReflectorMetadataProvider accesorProvider:
WriteObject(stream, accesorProvider);
break;
case Stream st:
if (st.Length > int.MaxValue)
throw new InvalidOperationException("Can not serialize more than 2GB of data for an stream");
WriteLenght(stream, (int)st.Length, Types.TYPE_STREAM_8, Types.TYPE_STREAM_16, Types.TYPE_STREAM_32);
WriteStream(stream, st);
break;
default:
if (type.IsEnum)
{
WriteInteger(stream, System.Convert.ToInt32(obj));
}
else
{
WriteObject(stream, obj, type);
}
break;
}
}
19
Source : BinaryConvert.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public static object ConvertTo(Type type, object value)
{
if (value != null && type != null)
{
var valueType = value.GetType();
if (valueType != type)
{
Type nullable = Nullable.GetUnderlyingType(type);
if (nullable != null)
{
if (nullable != valueType)
{
value = nullable.IsEnum ?
Enum.ToObject(nullable, value) :
System.Convert.ChangeType(value, nullable);
}
}
else if (type.IsEnum)
{
value = Enum.ToObject(type, value);
}
else if (!type.IsreplacedignableFrom(valueType))
{
value = System.Convert.ChangeType(value, type);
}
}
}
return value;
}
19
Source : TypeExtensions.cs
with GNU General Public License v3.0
from AnyStatus
with GNU General Public License v3.0
from AnyStatus
public static bool IsNumeric(this Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
case TypeCode.Object:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return Nullable.GetUnderlyingType(type).IsNumeric();
}
return false;
default:
return false;
}
}
19
Source : ConvertUtil.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public static T GetTypedCellValue<T>(object value)
{
if (value == null)
return default(T);
var fromType = value.GetType();
var toType = typeof(T);
var toNullableUnderlyingType = (TypeCompat.IsGenericType(toType) && toType.GetGenericTypeDefinition() == typeof(Nullable<>))
? Nullable.GetUnderlyingType(toType)
: null;
if (fromType == toType || fromType == toNullableUnderlyingType)
return (T)value;
// if converting to nullable struct and input is blank string, return null
if (toNullableUnderlyingType != null && fromType == typeof(string) && ((string)value).Trim() == string.Empty)
return default(T);
toType = toNullableUnderlyingType ?? toType;
if (toType == typeof(DateTime))
{
if (value is double)
return (T)(object)(DateTime.FromOADate((double)value));
if (fromType == typeof(TimeSpan))
return ((T)(object)(new DateTime(((TimeSpan)value).Ticks)));
if (fromType == typeof(string))
return (T)(object)DateTime.Parse(value.ToString());
}
else if (toType == typeof(TimeSpan))
{
if (value is double)
return (T)(object)(new TimeSpan(DateTime.FromOADate((double)value).Ticks));
if (fromType == typeof(DateTime))
return ((T)(object)(new TimeSpan(((DateTime)value).Ticks)));
if (fromType == typeof(string))
return (T)(object)TimeSpan.Parse(value.ToString());
}
return (T)Convert.ChangeType(value, toType);
}
19
Source : ConvertUtilTest.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
internal T GetTypedValue<T>(object v)
{
if (v == null)
{
return default(T);
}
Type fromType = v.GetType();
Type toType = typeof(T);
Type toType2 = (TypeCompat.IsGenericType(toType) && toType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
? Nullable.GetUnderlyingType(toType)
: null;
if (fromType == toType || fromType == toType2)
{
return (T)v;
}
var cnv = TypeDescriptor.GetConverter(fromType);
if (toType == typeof(DateTime) || toType2 == typeof(DateTime)) //Handle dates
{
if (fromType == typeof(TimeSpan))
{
return ((T)(object)(new DateTime(((TimeSpan)v).Ticks)));
}
else if (fromType == typeof(string))
{
DateTime dt;
if (DateTime.TryParse(v.ToString(), out dt))
{
return (T)(object)(dt);
}
else
{
return default(T);
}
}
else
{
if (cnv.CanConvertTo(typeof(double)))
{
return (T)(object)(DateTime.FromOADate((double)cnv.ConvertTo(v, typeof(double))));
}
else
{
return default(T);
}
}
}
else if (toType == typeof(TimeSpan) || toType2 == typeof(TimeSpan)) //Handle timespan
{
if (fromType == typeof(DateTime))
{
return ((T)(object)(new TimeSpan(((DateTime)v).Ticks)));
}
else if (fromType == typeof(string))
{
TimeSpan ts;
if (TimeSpan.TryParse(v.ToString(), out ts))
{
return (T)(object)(ts);
}
else
{
return default(T);
}
}
else
{
if (cnv.CanConvertTo(typeof(double)))
{
return (T)(object)(new TimeSpan(DateTime.FromOADate((double)cnv.ConvertTo(v, typeof(double))).Ticks));
}
else
{
try
{
// Issue 14682 -- "GetValue<decimal>() won't convert strings"
// As suggested, after all special cases, all .NET to do it's
// preferred conversion rather than simply returning the default
return (T)Convert.ChangeType(v, typeof(T));
}
catch (Exception)
{
// This was the previous behaviour -- no conversion is available.
return default(T);
}
}
}
}
else
{
if (cnv.CanConvertTo(toType))
{
return (T)cnv.ConvertTo(v, typeof(T));
}
else
{
if (toType2 != null)
{
toType = toType2;
if (cnv.CanConvertTo(toType))
{
return (T)cnv.ConvertTo(v, toType); //Fixes issue 15377
}
}
if (fromType == typeof(double) && toType == typeof(decimal))
{
return (T)(object)Convert.ToDecimal(v);
}
else if (fromType == typeof(decimal) && toType == typeof(double))
{
return (T)(object)Convert.ToDouble(v);
}
else
{
return default(T);
}
}
}
}
19
Source : TypeUtilities.cs
with MIT License
from areller
with MIT License
from areller
private static Type GetNullableUnderlyingType(Type type)
{
var underlying = Nullable.GetUnderlyingType(type);
if (underlying is null)
{
return type;
}
return underlying;
}
19
Source : IPropertyContainerExtensions.cs
with MIT License
from ark-mod
with MIT License
from ark-mod
public static TPropertyValue GetPropertyValue<TPropertyValue>(this IPropertyContainer self, ArkName name)
{
PropertyBase prop = null;
if (self.Properties.TryGetValue(name, out prop))
{
var value = prop.Value;
if (value == null) return default;
return Convert.ChangeType(value, Nullable.GetUnderlyingType(typeof(TPropertyValue)) ?? typeof(TPropertyValue));
}
else return default;
}
19
Source : DomainHelper.cs
with MIT License
from ark-mod
with MIT License
from ark-mod
public static void WriteDataStructure(IEnumerable<IGrouping<string, GameObject>> gameObjectGroups, string filePath)
{
//todo: refactor this code to make it less hackish
Func<Type, string> getTypeName = null;
getTypeName = new Func<Type, string>(t =>
{
var nt = Nullable.GetUnderlyingType(t);
if (nt != null) return $"{getTypeName(nt)}?";
if (t.IsGenericType) return $"{t.Name.Remove(t.Name.IndexOf('`'))}<{string.Join(",", t.GetGenericArguments().Select(at => getTypeName(at)))}>";
if (t.IsArray) return $"{getTypeName(t.GetElementType())}[{new string(',', t.GetArrayRank() - 1)}]";
return t.Name;
});
Func<int?, IEnumerable<PropertyBase>, string, List<string>, List<string>> recursivePropertyList = null;
recursivePropertyList = new Func<int?, IEnumerable<PropertyBase>, string, List<string>, List<string>>((gameObjectCount, props, path, list) =>
{
foreach (var grp in props.GroupBy(x => ArkName.Create(x.name.Name, x.index)))
{
var prop = path == null ? grp.Key.Token : $"{path}->{grp.Key}";
var proparrstruct = grp.OfType<StructArrayProperty>().Where(x => x.values.OfType<PropertyListStructProperty>().Any() == true);
var proplist = grp.OfType<PropertyListStructProperty>();
var optional = gameObjectCount != null && (gameObjectCount.Value > grp.Count() || gameObjectCount < 0);
if (proplist.Any()) recursivePropertyList(optional ? -1 : (int?)null, proplist.SelectMany(x => x.Properties.Values), prop, list);
else if(proparrstruct.Any()) recursivePropertyList(optional ? -1 : (int?)null, proparrstruct.SelectMany(x => x.values.OfType<PropertyListStructProperty>().SelectMany(y => y.Properties.Values)), prop, list);
else list.Add($"{prop} ({getTypeName(((dynamic)grp.First()).Value.GetType())}){(optional ? " [*]" : "")}");
}
return list;
});
var clreplacedes = gameObjectGroups
.Select(x =>
{
var c = x.Count();
return new
{
@clreplaced = x.Key,
count = c,
props = recursivePropertyList(c, x.SelectMany(y => y.Properties.Values), null, new List<string>()).OrderBy(y => y).ToArray()
};
})
.OrderBy(x => x.@clreplaced).Distinct().ToList();
using (var sw = new StreamWriter(filePath, false))
{
var serializer = new JsonSerializer { Formatting = Formatting.Indented };
serializer.Serialize(sw, clreplacedes);
}
}
19
Source : ShredObjectToDataTable.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
private object _convertColumnValue(object value)
{
if (value == null) return value;
var elementType = value.GetType();
var nullableType = Nullable.GetUnderlyingType(elementType);
if (nullableType != null)
{
elementType = nullableType;
}
if (elementType.IsEnum)
return value.ToString();
switch(value)
{
case LocalDate ld:
return ld.ToDateTimeUnspecified();
case LocalDateTime ldt:
return ldt.ToDateTimeUnspecified();
case Instant i:
return i.ToDateTimeUtc();
case OffsetDateTime odt:
return odt.ToDateTimeOffset();
case OffsetDate od:
return od.At(LocalTime.Midnight).ToDateTimeOffset();
case LocalTime lt:
return TimeSpan.FromTicks(lt.TickOfDay);
}
return value;
}
19
Source : EnumValueRetrieverAndComparer.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
private static object ConvertTheStringToAnEnum(string value, Type enumType)
{
if (!ThisIsNotANullableEnum(enumType) && string.IsNullOrWhiteSpace(value))
return null;
var underlyingType = Nullable.GetUnderlyingType(enumType);
if (underlyingType != null)
enumType = underlyingType;
Enum res = null;
foreach (Enum refValue in Enum.GetValues(enumType))
{
if (refValue.ToString() == value)
{
res = refValue;
break;
}
}
if (res != null) return res;
throw GetInvalidOperationException(value);
}
19
Source : SupportFlaggedEnum.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
return;
var queryEnumParams = operation.Parameters.OfType<OpenApiParameter>()
.Where(param => param.In == ParameterLocation.Query)
.Join(context.ApiDescription.ParameterDescriptions, o => o.Name, i => i.Name, (o, i) => new { o, i })
.Where(x =>
{
var t = x.i.Type;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
t = Nullable.GetUnderlyingType(t);
}
return t.IsEnum && t.IsDefined(typeof(FlagsAttribute), false);
})
.Select(x => x.o)
.ToArray();
foreach (var param in queryEnumParams)
{
var s = param.Schema;
param.Schema = new OpenApiSchema { Type = "array", Items = s };
param.Style = ParameterStyle.Simple;
param.Explode = false;
}
}
19
Source : SimpleTypeXlsxSerialiser.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public bool CanSerialiseType(Type valueType, Type itemType)
{
itemType = Nullable.GetUnderlyingType(itemType) ?? itemType;
return util.IsSimpleType(itemType);
}
19
Source : ShredObjectToDataTable.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
private Type _deriveColumnType(Type elementType)
{
var nullableType = Nullable.GetUnderlyingType(elementType);
if (nullableType != null)
{
elementType = nullableType;
}
if (_datetimeTypes.Contains(elementType))
elementType = typeof(DateTime);
if (_datetimeOffsetTypes.Contains(elementType))
elementType = typeof(DateTimeOffset);
if (_timeTypes.Contains(elementType))
elementType = typeof(TimeSpan);
if (elementType.IsEnum)
return typeof(string);
return elementType;
}
19
Source : NullableStructSerializerFactory.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override bool CanConvert(Type typeToConvert)
{
var t = Nullable.GetUnderlyingType(typeToConvert);
return t != null;
}
19
Source : NodatimeRetriverAndComparer.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public object Retrieve(KeyValuePair<string, string> keyValuePair, Type targetType, Type propertyType)
{
var t = Nullable.GetUnderlyingType(propertyType);
if (t != null)
{
if (string.IsNullOrWhiteSpace(keyValuePair.Value)) return null;
}
else t = propertyType;
if (t == typeof(LocalDate))
{
var res = LocalDatePattern.Iso.Parse(keyValuePair.Value);
if (res.Success) return res.Value;
var res4 = LocalDateTimePattern.ExtendedIso.Parse(keyValuePair.Value);
if (res4.Success && res4.Value.TimeOfDay == LocalTime.Midnight) return res4.Value.Date;
if (DateTime.TryParse(keyValuePair.Value, out var d) && d == d.Date)
{
return LocalDate.FromDateTime(d);
}
throw _getInvalidOperationException(keyValuePair.Value);
}
if (t == typeof(LocalDateTime))
{
var res = LocalDateTimePattern.ExtendedIso.Parse(keyValuePair.Value);
if (res.Success) return res.Value;
if (DateTime.TryParse(keyValuePair.Value, out var d))
{
return LocalDateTime.FromDateTime(d);
}
throw _getInvalidOperationException(keyValuePair.Value);
}
if (t == typeof(Instant))
{
var res = InstantPattern.ExtendedIso.Parse(keyValuePair.Value);
if (res.Success) return res.Value;
if (DateTime.TryParse(keyValuePair.Value, CultureInfo.CurrentCulture, DateTimeStyles.replacedumeUniversal | DateTimeStyles.AdjustToUniversal, out var d))
{
return Instant.FromDateTimeUtc(d);
}
throw _getInvalidOperationException(keyValuePair.Value);
}
if (t == typeof(LocalTime))
{
var res = LocalTimePattern.ExtendedIso.Parse(keyValuePair.Value);
if (!res.Success) throw _getInvalidOperationException(keyValuePair.Value);
return res.Value;
}
if (t == typeof(OffsetDateTime))
{
var res = OffsetDateTimePattern.ExtendedIso.Parse(keyValuePair.Value);
if (res.Success) return res.Value;
if (DateTimeOffset.TryParse(keyValuePair.Value, out var o))
{
return OffsetDateTime.FromDateTimeOffset(o);
}
throw _getInvalidOperationException(keyValuePair.Value);
}
throw new NotImplementedException();
}
19
Source : Check.cs
with MIT License
from arttonoyan
with MIT License
from arttonoyan
public static Type GetUnderlyingType(Type propType)
{
return System.Nullable.GetUnderlyingType(propType);
}
19
Source : CompilationProtocol.cs
with MIT License
from asc-community
with MIT License
from asc-community
private (Expression left, Expression right) EqualizeTypesIfAble(Expression left, Expression right)
{
if (left.Type == right.Type)
return (left, right);
Type? underlyingType = Nullable.GetUnderlyingType(left.Type);
bool nullable = (underlyingType is not null);
Type leftType = underlyingType ?? left.Type;
underlyingType = Nullable.GetUnderlyingType(right.Type);
nullable = nullable || (underlyingType is not null);
Type rightType = underlyingType ?? right.Type;
if (!typeLevelInHierarchy.ContainsKey(leftType) || !typeLevelInHierarchy.ContainsKey(rightType))
return (left, right);
var typeToCastTo = MaxType(leftType, rightType);
if (nullable && ((ConstantExpression)ConvertNaN(typeToCastTo)).Value == null)
{
typeToCastTo = typeof(Nullable<>).MakeGenericType(typeToCastTo);
}
left = ConvertType(left, typeToCastTo);
right = ConvertType(right, typeToCastTo);
return (left, right);
}
19
Source : CompilationProtocol.cs
with MIT License
from asc-community
with MIT License
from asc-community
public virtual Expression ConvertNaN(Type type)
{
if (NaNConverter is not null)
return NaNConverter(type);
type = Nullable.GetUnderlyingType(type) ?? type;
if (type == typeof(System.Numerics.Complex))
return Expression.Constant(new System.Numerics.Complex(double.NaN, 0));
if (type == typeof(double))
return Expression.Constant(double.NaN);
if (type == typeof(float))
return Expression.Constant(float.NaN);
if (type == typeof(long))
return Expression.Constant(null, typeof(long?));
if (type == typeof(BigInteger))
return Expression.Constant(null, typeof(BigInteger?));
if (type == typeof(int))
return Expression.Constant(null, typeof(int?));
if (type == typeof(object))
return Expression.Constant(null, typeof(object));
throw new InvalidProtocolProvided($"NaN conversion not implemented for {type}");
}
19
Source : CompilationProtocol.cs
with MIT License
from asc-community
with MIT License
from asc-community
public virtual Expression ConvertType(Expression expr, Type type)
{
if (TypeConverter is not null)
return TypeConverter(expr, type);
if (expr.Type == type)
return expr;
bool exprNullable = (Nullable.GetUnderlyingType(expr.Type) is not null) || (expr.Type == typeof(object));
bool typeNullable = (Nullable.GetUnderlyingType(type) is not null) || (type == typeof(object));
bool exprNaNisNaN = (((ConstantExpression)ConvertNaN(expr.Type)).Value is not null);
bool typeNaNisNaN = (((ConstantExpression)ConvertNaN(type)).Value is not null);
// ex. long? -> double
if (exprNullable && typeNaNisNaN)
{
return Expression.Condition(Expression.Equal(expr, Expression.Constant(null, expr.Type)),
ConvertNaN(type),
Expression.Convert(expr, type));
}
// ex. double -> long?
if (!exprNullable && exprNaNisNaN && typeNullable && !typeNaNisNaN)
{
MethodInfo isNaN = expr.Type.GetMethod("IsNaN") ?? throw new AngouriBugException($"IsNaN method expected for type {expr.Type}");
return Expression.Condition(Expression.Call(isNaN, expr),
Expression.Constant(null, type),
Expression.Convert(expr, type));
}
return Expression.Convert(expr, type);
}
19
Source : NullsafeQueryRewriter.cs
with MIT License
from AutoMapper
with MIT License
from AutoMapper
static bool IsNullableOrReferenceType(Type type)
{
return !type.GetTypeInfo().IsValueType || Nullable.GetUnderlyingType(type) != null;
}
19
Source : TypeExtensions.cs
with MIT License
from AutoMapper
with MIT License
from AutoMapper
public static bool IsLiteralType(this Type type)
{
if (type.IsNullableType())
type = Nullable.GetUnderlyingType(type);
return LiteralTypes.Contains(type);
}
19
Source : FilterHelper.cs
with MIT License
from AutoMapper
with MIT License
from AutoMapper
private static bool ConvertingUnderlyingTypeToNullable(Type original, Type conversion)
=> conversion.IsNullableType() && Nullable.GetUnderlyingType(conversion) == original;
See More Examples