Here are the examples of the csharp api System.Enum.GetUnderlyingType(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
435 Examples
19
Source : JsonMapper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
Type obj_type;
if (obj is ILRuntime.Runtime.Intepreter.ILTypeInstance)
{
obj_type = ((ILRuntime.Runtime.Intepreter.ILTypeInstance)obj).Type.ReflectionType;
}
else if(obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)
{
obj_type = ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)obj).ILInstance.Type.ReflectionType;
}
else
obj_type = obj.GetType();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName (entry.Key.ToString());
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
19
Source : Helper.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static R Parse<R>(this object value)
{
if (value == null || value is DBNull) return default(R);
if (value is R) return (R)value;
Type type = typeof(R);
if (type.IsEnum)
{
value = Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture);
return (R)Enum.ToObject(type, value);
}
else
{
return (R)Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
}
19
Source : Helper.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static object ToParameterValue(this object value)
{
if (value == null)
{
return DBNull.Value;
}
//TODO: not all needs mindatetime to be stored as null
//if (value is DateTime && (DateTime)value == DateTime.MinValue) return DBNull.Value;
if (value is Guid) if (Equals(value, Guid.Empty)) return DBNull.Value; else return value;
else if (value.GetType().IsEnum) return Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()));
else return value;
}
19
Source : ReaderCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static Func<IDataReader, T> ReaderToObject(IDataReader rdr)
{
MethodInfo rdrGetValueMethod = rdr.GetType().GetMethod("get_Item", new Type[] { typeof(int) });
Type[] args = { typeof(IDataReader) };
DynamicMethod method = new DynamicMethod("DynamicRead" + Guid.NewGuid().ToString(), typeof(T), args, typeof(Repository<T>).Module, true);
ILGenerator il = method.GetILGenerator();
LocalBuilder result = il.DeclareLocal(typeof(T)); //loc_0
il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Stloc_0, result); //Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index.
Label tryBlock = il.BeginExceptionBlock();
LocalBuilder valueCopy = il.DeclareLocal(typeof(object)); //declare local variable to store object value. loc_1
il.DeclareLocal(typeof(int)); //declare local variable to store index //loc_2
il.Emit(OpCodes.Ldc_I4_0); //load 0 in index
il.Emit(OpCodes.Stloc_2); //pop and save to local variable loc 2
//get FieldInfo of all properties
TableAttribute tableInfo = EnreplacedyCache.Get(typeof(T));
for (int i = 0; i < rdr.FieldCount; i++)
{
tableInfo.Columns.TryGetValue(rdr.GetName(i), out ColumnAttribute columnInfo);
if (columnInfo != null && columnInfo.SetMethod != null)
{
Label endIfLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0);//load the argument. Loads the argument at index 0 onto the evaluation stack.
il.Emit(OpCodes.Ldc_I4, i); //push field index as int32 to the stack. Pushes a supplied value of type int32 onto the evaluation stack as an int32.
il.Emit(OpCodes.Dup);//copy value
il.Emit(OpCodes.Stloc_2);//pop and save value to loc 2
il.Emit(OpCodes.Callvirt, rdrGetValueMethod); //Call rdr[i] method - Calls a late - bound method on an object, pushing the return value onto the evaluation stack.
//TODO: dynamic location using valueCopyLocal
il.Emit(OpCodes.Stloc_1); //pop the value and push in stack location 1
il.Emit(OpCodes.Ldloc_1); //load the variable in location 1
il.Emit(OpCodes.Isinst, typeof(DBNull)); //check whether value is null - Tests whether an object reference (type O) is an instance of a particular clreplaced.
il.Emit(OpCodes.Brtrue, endIfLabel); //go to end block if value is null
il.Emit(OpCodes.Ldloc_0); //load T result
il.Emit(OpCodes.Ldloc_1); //TODO: dynamic location using valueCopyLocal
//when Enum are without number values
if (columnInfo.Property.PropertyType.IsEnum)
{
Type numericType = Enum.GetUnderlyingType(columnInfo.Property.PropertyType);
if (rdr.GetFieldType(i) == typeof(string))
{
LocalBuilder stringEnumLocal = il.DeclareLocal(typeof(string));
il.Emit(OpCodes.Castclreplaced, typeof(string)); // stack is now [...][string]
il.Emit(OpCodes.Stloc, stringEnumLocal); // stack is now [...]
il.Emit(OpCodes.Ldtoken, columnInfo.Property.PropertyType); // stack is now [...][enum-type-token]
il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null);// stack is now [...][enum-type]
il.Emit(OpCodes.Ldloc, stringEnumLocal); // stack is now [...][enum-type][string]
il.Emit(OpCodes.Ldc_I4_1); // stack is now [...][enum-type][string][true]
il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [...][enum-as-object]
il.Emit(OpCodes.Unbox_Any, columnInfo.Property.PropertyType); // stack is now [...][typed-value]
}
else
{
ConvertValueToEnum(il, rdr.GetFieldType(i), columnInfo.Property.PropertyType, numericType);
}
}
else if (columnInfo.Property.PropertyType.IsValueType)
il.Emit(OpCodes.Unbox_Any, rdr.GetFieldType(i)); //type cast
// for nullable type fields
if (columnInfo.Property.PropertyType.IsGenericType && columnInfo.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var underlyingType = Nullable.GetUnderlyingType(columnInfo.Property.PropertyType);
il.Emit(OpCodes.Newobj, columnInfo.Property.PropertyType.GetConstructor(new Type[] { underlyingType }));
}
il.Emit(OpCodes.Callvirt, columnInfo.SetMethod);
il.Emit(OpCodes.Nop);
il.MarkLabel(endIfLabel);
}
}
il.BeginCatchBlock(typeof(Exception)); //begin try block. exception is in stack
il.Emit(OpCodes.Ldloc_2); //load index
il.Emit(OpCodes.Ldarg_0); //load argument reader
il.Emit(OpCodes.Ldloc_1); //load value //TODO: dynamic location using valueCopyLocal
il.EmitCall(OpCodes.Call, typeof(ReaderCache<T>).GetMethod(nameof(ReaderCache<T>.HandleException)), null); //call exception handler
il.EndExceptionBlock();
il.Emit(OpCodes.Ldloc, result);
il.Emit(OpCodes.Ret);
var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(IDataReader), typeof(T));
return (Func<IDataReader, T>)method.CreateDelegate(funcType);
}
19
Source : ReaderCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
private static Action<object, IDbCommand> AddParametersIL(object param, IDbCommand cmd)
{
Type pType = param.GetType();
Type[] args = { typeof(object), typeof(IDbCommand) };
DynamicMethod method = new DynamicMethod("DynamicAddParam" + Guid.NewGuid().ToString(), null, args, typeof(ParameterCache).Module, true);
ILGenerator il = method.GetILGenerator();
foreach (PropertyInfo property in pType.GetProperties())
{
il.Emit(OpCodes.Ldarg_1);//load the idbcommand. Loads the argument at index 0 onto the evaluation stack.
//name
il.Emit(OpCodes.Ldstr, property.Name);
//dbtype
//dynamic property will always return System.Object as property type. Get Type from the value
Type type = GetTypeOfDynamicProperty(property, param);
if (type.IsEnum) type = Enum.GetUnderlyingType(type);
if(TypeCache.TypeToDbType.TryGetValue(type, out DbType dbType))
il.Emit(OpCodes.Ldc_I4_S, (byte)dbType);
else
il.Emit(OpCodes.Ldc_I4_S, (byte)DbType.String); //TODO: fix when unkown type
//value
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, property.GetMethod);
//box if value type
if (property.PropertyType.IsValueType)
il.Emit(OpCodes.Box, property.PropertyType);
il.Emit(OpCodes.Call, addInParameter);
il.Emit(OpCodes.Nop);
}
il.Emit(OpCodes.Ret);
var actionType = System.Linq.Expressions.Expression.GetActionType(typeof(object), typeof(IDbCommand));
return (Action<object, IDbCommand>)method.CreateDelegate(actionType);
}
19
Source : ReaderCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static void AddParameters(object param, IDbCommand cmd)
{
if (param == null)
return;
Type pType = param.GetType();
foreach (PropertyInfo property in pType.GetProperties())
{
Type type = GetTypeOfDynamicProperty(property, param);
if (type.IsEnum) type = Enum.GetUnderlyingType(type);
if (!TypeCache.TypeToDbType.TryGetValue(type, out DbType dbType))
dbType = DbType.String; //TODO: fix when unkown type
cmd.AddInParameter(property.Name, dbType, property.GetValue(param));
}
}
19
Source : UacHelper.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
public static bool IsProcessElevated()
{
if (IsUacEnabled())
{
if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out IntPtr tokenHandle))
{
throw new ApplicationException("Could not get process token. Win32 Error Code: " + Marshal.GetLastWin32Error());
}
try
{
TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;
int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(elevationResult.GetType()));
uint returnedSize = 0;
IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
try
{
bool success = GetTokenInformation(tokenHandle, TokenInformationClreplaced.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
if (success)
{
elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
return isProcessAdmin;
}
else
{
throw new ApplicationException("Unable to determine the current elevation.");
}
}
finally
{
if (elevationTypePtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(elevationTypePtr);
}
}
}
finally
{
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
}
else
{
WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
WindowsPrincipal principal = new(idenreplacedy);
bool result = principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); // 0x200 = Domain Administrator
return result;
}
}
19
Source : EnumCache.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
internal static ulong ToUInt64Slow(Enum value)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(value.GetType())))
{
case TypeCode.SByte:
return ToUInt64((sbyte)(object)value);
case TypeCode.Byte:
return ToUInt64((byte)(object)value);
case TypeCode.Int16:
return ToUInt64((short)(object)value);
case TypeCode.UInt16:
return ToUInt64((ushort)(object)value);
case TypeCode.Int32:
return ToUInt64((int)(object)value);
case TypeCode.UInt32:
return ToUInt64((uint)(object)value);
case TypeCode.Int64:
return ToUInt64((long)(object)value);
case TypeCode.UInt64:
return ToUInt64((ulong)(object)value);
default:
throw new InvalidOperationException($"Invalid enum: {value.GetType()}");
}
}
19
Source : EnumCache.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
[SuppressMessage("ReSharper", "ConvertClosureToMethodGroup")]
public static bool IsEnumSigned(IntPtr typeHandle)
{
return _isEnumSigned.GetOrAdd(typeHandle, h => IsEnumSignedImpl(h));
static bool IsEnumSignedImpl(IntPtr h)
{
var type = TypeUtil.GetTypeFromHandle(h) ?? throw new InvalidOperationException("Could not resolve type from handle");
switch (Type.GetTypeCode(Enum.GetUnderlyingType(type)))
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
return true;
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return false;
default:
throw new InvalidOperationException($"Invalid enum: {type}");
}
}
}
19
Source : CopyObjectExtensions.cs
with MIT License
from adospace
with MIT License
from adospace
public static void CopyPropertiesTo(this object source, object dest, PropertyInfo[] destProps)
{
if (source.GetType().FullName != dest.GetType().FullName)
{
//can't copy state over a type with a different name: surely it's a different type
return;
}
var sourceProps = source.GetType()
.GetProperties()
.Where(x => x.CanRead)
.ToList();
foreach (var sourceProp in sourceProps)
{
var targetProperty = destProps.FirstOrDefault(x => x.Name == sourceProp.Name);
if (targetProperty != null)
{
var sourceValue = sourceProp.GetValue(source, null);
if (sourceValue != null && sourceValue.GetType().IsEnum)
{
sourceValue = Convert.ChangeType(sourceValue, Enum.GetUnderlyingType(sourceProp.PropertyType));
}
try
{
targetProperty.SetValue(dest, sourceValue, null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Unable to copy property '{targetProperty.Name}' of state ({source.GetType()}) to new state after hot reload (Exception: '{DumpExceptionMessage(ex)}')");
}
}
}
}
19
Source : DarksVMStack.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
public void ToTypedReference(uint pos, TypedRefPtr typedRef, Type type)
{
if(pos > topPos)
throw new ExecutionEngineException();
var section = sections[(int) (pos >> SectionSize)];
var index = pos & IndexMask;
if(type.IsEnum)
type = Enum.GetUnderlyingType(type);
if(type.IsPrimitive || type.IsPointer)
{
section[index].ToTypedReferencePrimitive(typedRef);
TypedReferenceHelpers.CastTypedRef(typedRef, type);
}
else
{
section[index].ToTypedReferenceObject(typedRef, type);
}
}
19
Source : DarksVMSlot.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
public static unsafe DarksVMSlot FromObject(object obj, Type type)
{
if(type.IsEnum)
{
var elemType = Enum.GetUnderlyingType(type);
return FromObject(Convert.ChangeType(obj, elemType), elemType);
}
switch(Type.GetTypeCode(type))
{
case TypeCode.Byte:
return new DarksVMSlot {u1 = (byte) obj};
case TypeCode.SByte:
return new DarksVMSlot {u1 = (byte) (sbyte) obj};
case TypeCode.Boolean:
return new DarksVMSlot {u1 = (byte) ((bool) obj ? 1 : 0)};
case TypeCode.UInt16:
return new DarksVMSlot {u2 = (ushort) obj};
case TypeCode.Int16:
return new DarksVMSlot {u2 = (ushort) (short) obj};
case TypeCode.Char:
return new DarksVMSlot {u2 = (char) obj};
case TypeCode.UInt32:
return new DarksVMSlot {u4 = (uint) obj};
case TypeCode.Int32:
return new DarksVMSlot {u4 = (uint) (int) obj};
case TypeCode.UInt64:
return new DarksVMSlot {u8 = (ulong) obj};
case TypeCode.Int64:
return new DarksVMSlot {u8 = (ulong) (long) obj};
case TypeCode.Single:
return new DarksVMSlot {r4 = (float) obj};
case TypeCode.Double:
return new DarksVMSlot {r8 = (double) obj};
default:
if(obj is Pointer)
return new DarksVMSlot {u8 = (ulong) Pointer.Unbox(obj)};
if(obj is IntPtr)
return new DarksVMSlot {u8 = (ulong) (IntPtr) obj};
if(obj is UIntPtr)
return new DarksVMSlot {u8 = (ulong) (UIntPtr) obj};
if(type.IsValueType)
return new DarksVMSlot {o = ValueTypeBox.Box(obj, type)};
return new DarksVMSlot {o = obj};
}
}
19
Source : DarksVMSlot.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
public unsafe object ToObject(Type type)
{
if(type.IsEnum)
return Enum.ToObject(type, ToObject(Enum.GetUnderlyingType(type)));
switch(Type.GetTypeCode(type))
{
case TypeCode.Byte:
return u1;
case TypeCode.SByte:
return (sbyte) u1;
case TypeCode.Boolean:
return u1 != 0;
case TypeCode.UInt16:
return u2;
case TypeCode.Int16:
return (short) u2;
case TypeCode.Char:
return (char) u2;
case TypeCode.UInt32:
return u4;
case TypeCode.Int32:
return (int) u4;
case TypeCode.UInt64:
return u8;
case TypeCode.Int64:
return (long) u8;
case TypeCode.Single:
return r4;
case TypeCode.Double:
return r8;
default:
if(type.IsPointer)
return Pointer.Box((void*) u8, type);
if(type == typeof(IntPtr))
return Platform.x64 ? new IntPtr((long) u8) : new IntPtr((int) u4);
if(type == typeof(UIntPtr))
return Platform.x64 ? new UIntPtr(u8) : new UIntPtr(u4);
return ValueTypeBox.Unbox(o);
}
}
19
Source : ProcessExtensions.cs
with GNU General Public License v3.0
from aglab2
with GNU General Public License v3.0
from aglab2
public static bool ReadValue<T>(this Process process, IntPtr addr, out T val) where T : struct
{
var type = typeof(T);
type = type.IsEnum ? Enum.GetUnderlyingType(type) : type;
val = default(T);
object val2;
if (!ReadValue(process, addr, type, out val2))
return false;
val = (T)val2;
return true;
}
19
Source : EnumUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static IList<T> GetFlagsValues<T>(T value) where T : struct
{
Type enumType = typeof(T);
if (!enumType.IsDefined(typeof(FlagsAttribute), false))
{
throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType));
}
Type underlyingType = Enum.GetUnderlyingType(value.GetType());
ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
IList<EnumValue<ulong>> enumNameValues = GetNamesAndValues<T>();
IList<T> selectedFlagsValues = new List<T>();
foreach (EnumValue<ulong> enumNameValue in enumNameValues)
{
if ((num & enumNameValue.Value) == enumNameValue.Value && enumNameValue.Value != 0)
{
selectedFlagsValues.Add((T)Convert.ChangeType(enumNameValue.Value, underlyingType, CultureInfo.CurrentCulture));
}
}
if (selectedFlagsValues.Count == 0 && enumNameValues.SingleOrDefault(v => v.Value == 0) != null)
{
selectedFlagsValues.Add(default(T));
}
return selectedFlagsValues;
}
19
Source : ConvertUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum)
{
PrimitiveTypeCode typeCode;
if (TypeCodeMap.TryGetValue(t, out typeCode))
{
isEnum = false;
return typeCode;
}
if (t.IsEnum())
{
isEnum = true;
return GetTypeCode(Enum.GetUnderlyingType(t));
}
// performance?
if (ReflectionUtils.IsNullableType(t))
{
Type nonNullable = Nullable.GetUnderlyingType(t);
if (nonNullable.IsEnum())
{
Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable));
isEnum = true;
return GetTypeCode(nullableUnderlyingType);
}
}
isEnum = false;
return PrimitiveTypeCode.Object;
}
19
Source : EnumUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static IList<EnumValue<TUnderlyingType>> GetNamesAndValues<TUnderlyingType>(Type enumType) where TUnderlyingType : struct
{
if (enumType == null)
{
throw new ArgumentNullException(nameof(enumType));
}
if (!enumType.IsEnum())
{
throw new ArgumentException("Type {0} is not an Enum.".FormatWith(CultureInfo.InvariantCulture, enumType), nameof(enumType));
}
IList<object> enumValues = GetValues(enumType);
IList<string> enumNames = GetNames(enumType);
IList<EnumValue<TUnderlyingType>> nameValues = new List<EnumValue<TUnderlyingType>>();
for (int i = 0; i < enumValues.Count; i++)
{
try
{
nameValues.Add(new EnumValue<TUnderlyingType>(enumNames[i], (TUnderlyingType)Convert.ChangeType(enumValues[i], typeof(TUnderlyingType), CultureInfo.CurrentCulture)));
}
catch (OverflowException e)
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}",
Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(enumValues[i], CultureInfo.InvariantCulture)), e);
}
}
return nameValues;
}
19
Source : Int64EnumTypeVisitor.cs
with MIT License
from aliencube
with MIT License
from aliencube
public override bool IsVisitable(Type type)
{
var isVisitable = this.IsVisitable(type, TypeCode.Int64) &&
type.IsUnflaggedEnumType() &&
!type.HasJsonConverterAttribute<StringEnumConverter>() &&
Enum.GetUnderlyingType(type) == typeof(long)
;
return isVisitable;
}
19
Source : Int16EnumTypeVisitor.cs
with MIT License
from aliencube
with MIT License
from aliencube
public override bool IsVisitable(Type type)
{
var isVisitable = this.IsVisitable(type, TypeCode.Int16) &&
type.IsUnflaggedEnumType() &&
!type.HasJsonConverterAttribute<StringEnumConverter>() &&
Enum.GetUnderlyingType(type) == typeof(short)
;
return isVisitable;
}
19
Source : Int32EnumTypeVisitor.cs
with MIT License
from aliencube
with MIT License
from aliencube
public override bool IsVisitable(Type type)
{
var isVisitable = this.IsVisitable(type, TypeCode.Int32) &&
type.IsUnflaggedEnumType() &&
!type.HasJsonConverterAttribute<StringEnumConverter>() &&
Enum.GetUnderlyingType(type) == typeof(int)
;
return isVisitable;
}
19
Source : PrimitiveObjectFormatter.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
return;
}
Type t = value.GetType();
int code;
if (TypeToJumpCode.TryGetValue(t, out code))
{
switch (code)
{
case 0:
writer.Write((bool)value);
return;
case 1:
writer.Write((char)value);
return;
case 2:
writer.WriteInt8((sbyte)value);
return;
case 3:
writer.WriteUInt8((byte)value);
return;
case 4:
writer.WriteInt16((Int16)value);
return;
case 5:
writer.WriteUInt16((UInt16)value);
return;
case 6:
writer.WriteInt32((Int32)value);
return;
case 7:
writer.WriteUInt32((UInt32)value);
return;
case 8:
writer.WriteInt64((Int64)value);
return;
case 9:
writer.WriteUInt64((UInt64)value);
return;
case 10:
writer.Write((Single)value);
return;
case 11:
writer.Write((double)value);
return;
case 12:
writer.Write((DateTime)value);
return;
case 13:
writer.Write((string)value);
return;
case 14:
writer.Write((byte[])value);
return;
default:
throw new MessagePackSerializationException("Not supported primitive object resolver. type:" + t.Name);
}
}
else
{
#if UNITY_2018_3_OR_NEWER && !NETFX_CORE
if (t.IsEnum)
#else
if (t.GetTypeInfo().IsEnum)
#endif
{
Type underlyingType = Enum.GetUnderlyingType(t);
var code2 = TypeToJumpCode[underlyingType];
switch (code2)
{
case 2:
writer.WriteInt8((sbyte)value);
return;
case 3:
writer.WriteUInt8((byte)value);
return;
case 4:
writer.WriteInt16((Int16)value);
return;
case 5:
writer.WriteUInt16((UInt16)value);
return;
case 6:
writer.WriteInt32((Int32)value);
return;
case 7:
writer.WriteUInt32((UInt32)value);
return;
case 8:
writer.WriteInt64((Int64)value);
return;
case 9:
writer.WriteUInt64((UInt64)value);
return;
default:
break;
}
}
else if (value is System.Collections.IDictionary)
{
// check IDictionary first
var d = value as System.Collections.IDictionary;
writer.WriteMapHeader(d.Count);
foreach (System.Collections.DictionaryEntry item in d)
{
this.Serialize(ref writer, item.Key, options);
this.Serialize(ref writer, item.Value, options);
}
return;
}
else if (value is System.Collections.ICollection)
{
var c = value as System.Collections.ICollection;
writer.WriteArrayHeader(c.Count);
foreach (var item in c)
{
this.Serialize(ref writer, item, options);
}
return;
}
}
throw new MessagePackSerializationException("Not supported primitive object resolver. type:" + t.Name);
}
19
Source : DynamicEnumResolver.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
private static TypeInfo BuildType(Type enumType)
{
Type underlyingType = Enum.GetUnderlyingType(enumType);
Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(enumType);
using (MonoProtection.EnterRefEmitLock())
{
TypeBuilder typeBuilder = Dynamicreplacedembly.Value.DefineType("MessagePack.Formatters." + enumType.FullName.Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });
// void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options);
{
MethodBuilder method = typeBuilder.DefineMethod(
"Serialize",
MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
null,
new Type[] { typeof(MessagePackWriter).MakeByRefType(), enumType, typeof(MessagePackSerializerOptions) });
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Call, typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { underlyingType }));
il.Emit(OpCodes.Ret);
}
// T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options);
{
MethodBuilder method = typeBuilder.DefineMethod(
"Deserialize",
MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
enumType,
new Type[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) });
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Call, typeof(MessagePackReader).GetRuntimeMethod("Read" + underlyingType.Name, Type.EmptyTypes));
il.Emit(OpCodes.Ret);
}
return typeBuilder.CreateTypeInfo();
}
}
19
Source : TypeExtensions.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static Type GetUnderlyingType(this Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (type.IsNullable())
type = type.GetGenericArguments()[0];
if (type.IsEnum)
type = Enum.GetUnderlyingType(type);
return type;
}
19
Source : TypeExtensions.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static bool IsSameOrParent(Type parent, Type child)
{
if (parent == null) throw new ArgumentNullException("parent");
if (child == null) throw new ArgumentNullException("child");
if (parent == child ||
child.IsEnum && Enum.GetUnderlyingType(child) == parent ||
child.IsSubclreplacedOf(parent))
{
return true;
}
if (parent.IsInterface)
{
var interfaces = child.GetInterfaces();
foreach (var t in interfaces)
if (t == parent)
return true;
}
return false;
}
19
Source : ProvideSourceControlCommand.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
private static int GetEnumValue(object commandValue)
{
if (commandValue == null)
return 0;
Type enumType = commandValue.GetType();
Type undertype = Enum.GetUnderlyingType(enumType);
commandValue = Convert.ChangeType(commandValue, undertype);
return (int)commandValue;
}
19
Source : EnumMarshalerFactory.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
public bool CanMarshal(Type type)
{
if (!type.IsEnum)
{
return false;
}
Type underlyingType = Enum.GetUnderlyingType(type);
return MarshalingManager.IsKnownType(underlyingType);
}
19
Source : EnumMarshalerFactory.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
public bool TryCreate(Type type, out ITypeMarshaler typeMarshaler)
{
if (!type.IsEnum)
{
typeMarshaler = null;
return false;
}
Type underlyingType = Enum.GetUnderlyingType(type);
ITypeMarshaler underlyingMarshaler = MarshalingManager.GetMarshaler(underlyingType);
if (underlyingMarshaler == null)
{
typeMarshaler = null;
return false;
}
typeMarshaler = new EnumMarshaler(type, underlyingMarshaler);
return true;
}
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 : FlagsEnumEditor.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
private void FillList()
{
// Check if editable object is of type Enum
if(!(this._editType.IsEnum))
{
throw (new ArgumentException(SR.ExceptionEditorUITypeEditorInapplicable));
}
// Check underlying type
if(Enum.GetUnderlyingType(this._editType) != typeof(Int32))
{
throw (new ArgumentException(SR.ExceptionEditorUITypeEditorInt32ApplicableOnly));
}
// Convert enumeration value to Int32
Int32 editValueInt32 = 0;
if(_editValue != null)
{
editValueInt32 = (Int32)_editValue;
}
// Fill list with all possible values in the enumeration
foreach(object enumValue in Enum.GetValues(this._editType))
{
// Add items into list except the enum value zero
Int32 currentValueInt32 = (Int32)enumValue;
if(currentValueInt32 != 0)
{
bool isChecked = (editValueInt32 & currentValueInt32) == currentValueInt32;
this.Items.Add(Enum.GetName(this._editType, enumValue), isChecked);
}
}
}
19
Source : JsonMapper.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
private static void WriteValue(object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException(String.Format("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType()));
if (obj == null)
{
writer.Write(null);
return;
}
if (obj is IJsonWrapper)
{
if (writer_is_private)
writer.TextWriter.Write(((IJsonWrapper) obj).ToJson());
else
((IJsonWrapper) obj).ToJson(writer);
return;
}
if (obj is String)
{
writer.Write((string) obj);
return;
}
if (obj is Double)
{
writer.Write((double) obj);
return;
}
if (obj is Single)
{
writer.Write((float) obj);
return;
}
if (obj is Int32)
{
writer.Write((int) obj);
return;
}
if (obj is Boolean)
{
writer.Write((bool) obj);
return;
}
if (obj is Int64)
{
writer.Write((long) obj);
return;
}
if (obj is Array)
{
writer.WriteArrayStart();
foreach (object elem in (Array) obj)
WriteValue(elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd();
return;
}
if (obj is IList)
{
writer.WriteArrayStart();
foreach (object elem in (IList) obj)
WriteValue(elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd();
return;
}
#if UNITY_2018_3_OR_NEWER
if (obj is IDictionary dictionary) {
#else
if (obj is IDictionary)
{
var dictionary = obj as IDictionary;
#endif
writer.WriteObjectStart();
foreach (DictionaryEntry entry in dictionary)
{
#if UNITY_2018_3_OR_NEWER
var propertyName = entry.Key is string key ?
key
: Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
#else
var propertyName = entry.Key is string? (entry.Key as string) : Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
#endif
writer.WritePropertyName(propertyName);
WriteValue(entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd();
return;
}
Type obj_type = obj.GetType();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey(obj_type))
{
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter(obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey(obj_type))
{
ExporterFunc exporter = base_exporters_table[obj_type];
exporter(obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum)
{
Type e_type = Enum.GetUnderlyingType(obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write((ulong) obj);
else
writer.Write((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties(obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart();
writer.WritePropertyName("_t");
writer.Write(obj_type.Name);
foreach (PropertyMetadata p_data in props)
{
var skipAttributesList = p_data.Info.GetCustomAttributes(typeof (IgnoreDataMemberAttribute), true);
var skipAttributes = skipAttributesList as ICollection<Attribute>;
if (skipAttributes.Count > 0)
{
continue;
}
if (p_data.IsField)
{
writer.WritePropertyName(p_data.Info.Name);
WriteValue(((FieldInfo) p_data.Info).GetValue(obj),
writer, writer_is_private, depth + 1);
}
else
{
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead)
{
writer.WritePropertyName(p_data.Info.Name);
WriteValue(p_info.GetValue(obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd();
}
19
Source : RealBinaryMapping.Read.cs
with Apache License 2.0
from AntonioDePau
with Apache License 2.0
from AntonioDePau
private object ReadProperty(MappingReadArgs args, Type type, MyProperty property)
{
if (type != typeof(bool))
args.BitIndex = 0;
if (mappings.TryGetValue(type, out var mapping))
{
args.DataAttribute = property.DataInfo;
return mapping.Reader(args);
}
else if (type.IsEnum)
{
var underlyingType = Enum.GetUnderlyingType(type);
if (!mappings.TryGetValue(underlyingType, out mapping))
throw new InvalidDataException($"The enum {type.Name} has an unsupported size.");
args.DataAttribute = property.DataInfo;
return mapping.Reader(args);
}
else if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>)))
{
var listType = type.GetGenericArguments().FirstOrDefault();
if (listType == null)
throw new InvalidDataException($"The list {property.MemberInfo.Name} does not have any specified type.");
var addMethod = type.GetMethod("Add");
var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(listType));
for (int i = 0; i < args.Count; i++)
{
var oldPosition = (int)args.Reader.BaseStream.Position;
var item = ReadProperty(args, listType, property);
addMethod.Invoke(list, new[] { item });
var newPosition = args.Reader.BaseStream.Position;
args.Reader.BaseStream.Position += Math.Max(0, property.DataInfo.Stride - (newPosition - oldPosition));
}
return list;
}
else if (type.IsArray)
{
if (type.GetArrayRank() > 1)
throw new NotImplementedException("Arrays with a rank greater than one are not currently supported.");
var arrayType = type.GetElementType();
if (arrayType == null)
throw new InvalidDataException($"Unable to get the underlying type of {type.Name}.");
var array = Array.CreateInstance(arrayType, args.Count);
if (arrayType.IsEnum)
{
for (var i = 0; i < args.Count; i++)
{
var oldPosition = (int)args.Reader.BaseStream.Position;
var item = ReadProperty(args, arrayType, property);
array.SetValue(Enum.ToObject(arrayType, item), i);
var newPosition = args.Reader.BaseStream.Position;
args.Reader.BaseStream.Position += Math.Max(0, property.DataInfo.Stride - (newPosition - oldPosition));
}
}
else
{
for (var i = 0; i < args.Count; i++)
{
var oldPosition = (int)args.Reader.BaseStream.Position;
var item = ReadProperty(args, arrayType, property);
array.SetValue(item, i);
var newPosition = args.Reader.BaseStream.Position;
args.Reader.BaseStream.Position += Math.Max(0, property.DataInfo.Stride - (newPosition - oldPosition));
}
}
return array;
}
else
{
return ReadRawObject(args.Reader, Activator.CreateInstance(type), (int)args.Reader.BaseStream.Position);
}
}
19
Source : RealBinaryMapping.Write.cs
with Apache License 2.0
from AntonioDePau
with Apache License 2.0
from AntonioDePau
private void WriteProperty(MappingWriteArgs args, object value, Type type, MyProperty property)
{
if (type != typeof(bool))
FlushBitField(args);
if (mappings.TryGetValue(type, out var mapping))
{
args.Item = value;
args.DataAttribute = property.DataInfo;
mapping.Writer(args);
}
else if (type.IsEnum)
{
var underlyingType = Enum.GetUnderlyingType(type);
if (!mappings.TryGetValue(underlyingType, out mapping))
throw new InvalidDataException($"The enum {type.Name} has an unsupported size.");
args.DataAttribute = property.DataInfo;
args.Item = value;
mapping.Writer(args);
}
else if (type.CanEnumerate())
{
Type itemType;
if (type.IsArray)
{
if (value is Array array && array.Rank > 1)
throw new NotImplementedException("Arrays with a rank greater than one are not currently supported.");
itemType = type.GetElementType();
}
else
{
itemType = type.GetGenericArguments().FirstOrDefault();
}
if (itemType == null)
throw new InvalidDataException($"The list {property.MemberInfo.Name} does not have any specified type.");
var missing = args.Count;
foreach (var item in value as IEnumerable)
{
if (missing-- < 1)
break;
WriteObject(args, item, itemType, property);
}
while (missing-- > 0)
{
var item = Activator.CreateInstance(itemType);
WriteObject(args, item, itemType, property);
}
}
else
{
WriteObject(args.Writer, value, (int)args.Writer.BaseStream.Position);
}
}
19
Source : Lz4Compression.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static TypeInfo FindLZ4Level(IEnumerable<TypeInfo> types)
{
const string fullName = "K4os.Compression.LZ4.LZ4Level";
foreach (var type in types)
{
if (type.FullName is null || !type.FullName.Equals(fullName))
continue;
if (type.IsPublic && type.IsEnum && Enum.GetUnderlyingType(type) == typeof(int))
return type;
break;
}
throw new Exception($"{fullName} as a public enum with an int backing was not found");
}
19
Source : TestUtils.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
private static long GetHdfTypeIdFromType(Type type)
{
var elementType = type.IsArray ? type.GetElementType() : type;
if (elementType == typeof(bool))
return H5T.NATIVE_UINT8;
else if (elementType == typeof(byte))
return H5T.NATIVE_UINT8;
else if (elementType == typeof(sbyte))
return H5T.NATIVE_INT8;
else if (elementType == typeof(ushort))
return H5T.NATIVE_UINT16;
else if (elementType == typeof(short))
return H5T.NATIVE_INT16;
else if (elementType == typeof(uint))
return H5T.NATIVE_UINT32;
else if (elementType == typeof(int))
return H5T.NATIVE_INT32;
else if (elementType == typeof(ulong))
return H5T.NATIVE_UINT64;
else if (elementType == typeof(long))
return H5T.NATIVE_INT64;
else if (elementType == typeof(float))
return H5T.NATIVE_FLOAT;
else if (elementType == typeof(double))
return H5T.NATIVE_DOUBLE;
// issues: https://en.wikipedia.org/wiki/Long_double
//else if (elementType == typeof(decimal))
// return H5T.NATIVE_LDOUBLE;
else if (elementType.IsEnum)
{
var baseTypeId = TestUtils.GetHdfTypeIdFromType(Enum.GetUnderlyingType(elementType));
var typeId = H5T.enum_create(baseTypeId);
foreach (var value in Enum.GetValues(type))
{
var value_converted = Convert.ToInt64(value);
var name = Enum.GetName(type, value_converted);
var handle = GCHandle.Alloc(value_converted, GCHandleType.Pinned);
H5T.enum_insert(typeId, name, handle.AddrOfPinnedObject());
}
return typeId;
}
else if (elementType == typeof(string) || elementType == typeof(IntPtr))
{
var typeId = H5T.copy(H5T.C_S1);
H5T.set_size(typeId, H5T.VARIABLE);
H5T.set_cset(typeId, H5T.cset_t.UTF8);
return typeId;
}
else if (elementType.IsValueType && !elementType.IsPrimitive)
{
var typeId = H5T.create(H5T.clreplaced_t.COMPOUND, new IntPtr(Marshal.SizeOf(elementType)));
foreach (var fieldInfo in elementType.GetFields())
{
var fieldType = TestUtils.GetHdfTypeIdFromType(fieldInfo.FieldType);
var attribute = fieldInfo.GetCustomAttribute<H5NameAttribute>(true);
var hdfFieldName = attribute is not null ? attribute.Name : fieldInfo.Name;
H5T.insert(typeId, hdfFieldName, Marshal.OffsetOf(elementType, fieldInfo.Name), fieldType);
if (H5I.is_valid(fieldType) > 0)
H5T.close(fieldType);
}
return typeId;
}
else
{
throw new NotSupportedException();
}
}
19
Source : DriverSettings.cs
with Apache License 2.0
from aquality-automation
with Apache License 2.0
from aquality-automation
private object ParseEnumValue(Type propertyType, object optionValue)
{
return optionValue is string
? Enum.Parse(propertyType, optionValue.ToString(), ignoreCase: true)
: Enum.ToObject(propertyType, Convert.ChangeType(optionValue, Enum.GetUnderlyingType(propertyType)));
}
19
Source : DriverSettings.cs
with Apache License 2.0
from aquality-automation
with Apache License 2.0
from aquality-automation
private bool IsEnumValue(Type propertyType, object optionValue)
{
var valuereplacedtring = optionValue.ToString();
if (!propertyType.IsEnum || string.IsNullOrEmpty(valuereplacedtring))
{
return false;
}
var normalizedValue = char.ToUpper(valuereplacedtring[0]) +
(valuereplacedtring.Length > 1 ? valuereplacedtring.Substring(1) : string.Empty);
return propertyType.IsEnumDefined(normalizedValue)
|| propertyType.IsEnumDefined(valuereplacedtring)
|| (IsValueOfIntegralNumericType(optionValue)
&& propertyType.IsEnumDefined(Convert.ChangeType(optionValue, Enum.GetUnderlyingType(propertyType))));
}
19
Source : JsonMapper.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// See if there's a custom exporter for the base clreplaced of the object
foreach (var type in custom_exporters_table.Keys)
{
if (obj_type.IsSubclreplacedOf(type))
{
ExporterFunc exporter = custom_exporters_table[type];
exporter(obj, writer);
return;
}
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
19
Source : EnumHelper.cs
with MIT License
from bbepis
with MIT License
from bbepis
public static object GetValues( Type flagType, string commaSeparatedStringValue )
{
var attr = (FlagsAttribute)flagType.GetCustomAttributes( typeof( FlagsAttribute ), false ).FirstOrDefault();
if( attr == null )
{
return Enum.Parse( flagType, commaSeparatedStringValue, true );
}
else
{
var stringValues = commaSeparatedStringValue.Split( new char[] { ';', ' ' }, StringSplitOptions.RemoveEmptyEntries );
var validEnumValues = Enum.GetValues( flagType );
var underlyingType = Enum.GetUnderlyingType( flagType );
long flagValues = 0;
foreach( var stringValue in stringValues )
{
bool found = false;
foreach( var validEnumValue in validEnumValues )
{
var validStringValue = Enum.GetName( flagType, validEnumValue );
if( string.Equals( stringValue, validStringValue, StringComparison.OrdinalIgnoreCase ) )
{
var validInteger = Convert.ToInt64( validEnumValue );
flagValues |= validInteger;
found = true;
}
}
if( !found )
{
throw new ArgumentException( $"Requested value '{stringValue}' was not found." );
}
}
return Convert.ChangeType( flagValues, Enum.GetUnderlyingType( flagType ) );
}
}
19
Source : System_EnumWrap.cs
with MIT License
from bjfumac
with MIT License
from bjfumac
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetUnderlyingType(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
System.Type arg0 = ToLua.CheckMonoType(L, 1);
System.Type o = System.Enum.GetUnderlyingType(arg0);
ToLua.Push(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
19
Source : IntToVisibilityConverter.cs
with GNU General Public License v2.0
from BlackTasty
with GNU General Public License v2.0
from BlackTasty
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Enum)
{
var underlyingType = Enum.GetUnderlyingType(value.GetType());
value = System.Convert.ChangeType(value, underlyingType);
}
string parameterParsed = parameter?.ToString() ?? "";
if (!string.IsNullOrEmpty(parameterParsed))
{
string[] parameterValues = parameterParsed.Split(';');
for (int i = 0; i < parameterValues.Length; i++)
{
if (int.Parse(value?.ToString() ?? "-1") == int.Parse(parameterValues[i]))
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}
19
Source : IntToBooleanConverter.cs
with GNU General Public License v2.0
from BlackTasty
with GNU General Public License v2.0
from BlackTasty
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Enum)
{
var underlyingType = Enum.GetUnderlyingType(value.GetType());
value = System.Convert.ChangeType(value, underlyingType);
}
return Parser.TryParse(value.ToString(), -1) >= Parser.TryParse(parameter.ToString(), -1);
}
19
Source : EnumToIntConverter.cs
with GNU General Public License v2.0
from BlackTasty
with GNU General Public License v2.0
from BlackTasty
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var underlyingType = Enum.GetUnderlyingType(value.GetType());
int test = (int)System.Convert.ChangeType(value, underlyingType);
return (int)System.Convert.ChangeType(value, underlyingType);
}
19
Source : ExactIntToBooleanConverter.cs
with GNU General Public License v2.0
from BlackTasty
with GNU General Public License v2.0
from BlackTasty
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Enum)
{
var underlyingType = Enum.GetUnderlyingType(value.GetType());
value = System.Convert.ChangeType(value, underlyingType);
}
return Parser.TryParse(value.ToString(), -1) == Parser.TryParse(parameter.ToString(), -1);
}
19
Source : PersistentArgument.cs
with MIT License
from BLUDRAG
with MIT License
from BLUDRAG
public static PersistentArgumentType GetArgumentType(Type type, out string replacedemblyQualifiedName, out int linkIndex)
{
linkIndex = 0;
replacedemblyQualifiedName = null;
if (type == typeof(bool)) return PersistentArgumentType.Bool;
else if (type == typeof(string)) return PersistentArgumentType.String;
else if (type == typeof(int)) return PersistentArgumentType.Int;
else if (type == typeof(float)) return PersistentArgumentType.Float;
else if (type == typeof(Vector2)) return PersistentArgumentType.Vector2;
else if (type == typeof(Vector3)) return PersistentArgumentType.Vector3;
else if (type == typeof(Vector4)) return PersistentArgumentType.Vector4;
else if (type == typeof(Quaternion)) return PersistentArgumentType.Quaternion;
else if (type == typeof(Color)) return PersistentArgumentType.Color;
else if (type == typeof(Color32)) return PersistentArgumentType.Color32;
else if (type == typeof(Rect)) return PersistentArgumentType.Rect;
else if (type.IsEnum)
{
if (System.Enum.GetUnderlyingType(type) == typeof(int))
{
replacedemblyQualifiedName = type.replacedemblyQualifiedName;
return PersistentArgumentType.Enum;
}
else return PersistentArgumentType.None;
}
else if (type == typeof(Object) || type.IsSubclreplacedOf(typeof(Object)))
{
replacedemblyQualifiedName = type.replacedemblyQualifiedName;
return PersistentArgumentType.Object;
}
else
{
replacedemblyQualifiedName = type.replacedemblyQualifiedName;
#if UNITY_EDITOR
PersistentArgumentType linkType;
if (Editor.DrawerState.Current.TryGetLinkable(type, out linkIndex, out linkType))
return linkType;
#endif
return PersistentArgumentType.ReturnValue;
}
}
19
Source : PersistentCall.cs
with MIT License
from BLUDRAG
with MIT License
from BLUDRAG
public static bool IsSupportedNative(Type type)
{
return
type == typeof(bool) ||
type == typeof(string) ||
type == typeof(int) ||
(type.IsEnum && Enum.GetUnderlyingType(type) == typeof(int)) ||
type == typeof(float) ||
type == typeof(Vector2) ||
type == typeof(Vector3) ||
type == typeof(Vector4) ||
type == typeof(Quaternion) ||
type == typeof(Color) ||
type == typeof(Color32) ||
type == typeof(Rect) ||
type == typeof(Object) || type.IsSubclreplacedOf(typeof(Object));
}
19
Source : DefinitionGenerator.cs
with MIT License
from BoltBait
with MIT License
from BoltBait
private static string GetInheritance(this Type type)
{
if (type.IsEnum)
{
Type baseType = Enum.GetUnderlyingType(type);
return (baseType != typeof(int)) ? " : " + baseType.GetDisplayName() : string.Empty;
}
IEnumerable<Type> directInterfaces = type.GetDirectBaseInterfaces().Where(i => i.IsVisibleInterface());
IEnumerable<Type> inheritedInterfaces = directInterfaces.SelectMany(i => i.GetInterfaces());
IEnumerable<string> allInheritance = directInterfaces.Concat(inheritedInterfaces)
.Distinct()
.Select(i => i.GetDisplayName())
.OrderBy(s => s);
if (type.IsClreplaced && type != typeof(object) && type.BaseType != typeof(object))
{
allInheritance = allInheritance.Prepend(type.BaseType.GetDisplayName());
}
return allInheritance.Any()
? " : " + allInheritance.Join(", ")
: string.Empty;
}
19
Source : Extensions.cs
with MIT License
from BoltBait
with MIT License
from BoltBait
internal static string GetEnumValue(this FieldInfo field)
{
object value = field.GetValue(null);
Type type = Enum.GetUnderlyingType(field.FieldType);
return Convert.ChangeType(value, type).ToString();
}
19
Source : DictionaryKeyUtility.cs
with MIT License
from BrunoS3D
with MIT License
from BrunoS3D
public static string GetDictionaryKeyString(object key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
Type type = key.GetType();
if (!KeyTypeSupportsPersistentPaths(type))
{
string keyString;
if (!ObjectsToTempKeys.TryGetValue(key, out keyString))
{
keyString = (tempKeyCounter++).ToString();
var str = "{temp:" + keyString + "}";
ObjectsToTempKeys[key] = str;
TempKeysToObjects[str] = key;
}
return keyString;
}
IDictionaryKeyPathProvider keyPathProvider;
if (TypeToKeyPathProviders.TryGetValue(type, out keyPathProvider))
{
var keyStr = keyPathProvider.GetPathStringFromKey(key);
string error = null;
bool validPath = true;
if (keyStr == null || keyStr.Length == 0)
{
validPath = false;
error = "String is null or empty";
}
if (validPath)
{
for (int i = 0; i < keyStr.Length; i++)
{
var c = keyStr[i];
if (char.IsLetterOrDigit(c) || AllowedSpecialKeyStrChars.Contains(c)) continue;
validPath = false;
error = "Invalid character '" + c + "' at index " + i;
break;
}
}
if (!validPath)
{
throw new ArgumentException("Invalid key path '" + keyStr + "' given by provider '" + keyPathProvider.GetType().GetNiceFullName() + "': " + error);
}
return "{id:" + ProviderToID[keyPathProvider] + ":" + keyStr + "}";
}
if (type.IsEnum)
{
Type backingType = Enum.GetUnderlyingType(type);
if (backingType == typeof(ulong))
{
ulong value = Convert.ToUInt64(key);
return "{" + value.ToString("D", CultureInfo.InvariantCulture) + "eu}";
}
else
{
long value = Convert.ToInt64(key);
return "{" + value.ToString("D", CultureInfo.InvariantCulture) + "es}";
}
}
if (type == typeof(string)) return "{\"" + key + "\"}";
if (type == typeof(char)) return "{'" + ((char)key).ToString(CultureInfo.InvariantCulture) + "'}";
if (type == typeof(byte)) return "{" + ((byte)key).ToString("D", CultureInfo.InvariantCulture) + "ub}";
if (type == typeof(sbyte)) return "{" + ((sbyte)key).ToString("D", CultureInfo.InvariantCulture) + "sb}";
if (type == typeof(ushort)) return "{" + ((ushort)key).ToString("D", CultureInfo.InvariantCulture) + "us}";
if (type == typeof(short)) return "{" + ((short)key).ToString("D", CultureInfo.InvariantCulture) + "ss}";
if (type == typeof(uint)) return "{" + ((uint)key).ToString("D", CultureInfo.InvariantCulture) + "ui}";
if (type == typeof(int)) return "{" + ((int)key).ToString("D", CultureInfo.InvariantCulture) + "si}";
if (type == typeof(ulong)) return "{" + ((ulong)key).ToString("D", CultureInfo.InvariantCulture) + "ul}";
if (type == typeof(long)) return "{" + ((long)key).ToString("D", CultureInfo.InvariantCulture) + "sl}";
if (type == typeof(float)) return "{" + ((float)key).ToString("R", CultureInfo.InvariantCulture) + "fl}";
if (type == typeof(double)) return "{" + ((double)key).ToString("R", CultureInfo.InvariantCulture) + "dl}";
if (type == typeof(decimal)) return "{" + ((decimal)key).ToString("G", CultureInfo.InvariantCulture) + "dc}";
if (type == typeof(Guid)) return "{" + ((Guid)key).ToString("N", CultureInfo.InvariantCulture) + "gu}";
throw new NotImplementedException("Support has not been implemented for the supported dictionary key type '" + type.GetNiceName() + "'.");
}
19
Source : SharedTypeExtensions.cs
with Apache License 2.0
from bubibubi
with Apache License 2.0
from bubibubi
public static Type UnwrapEnumType(this Type type)
{
var isNullable = type.IsNullableType();
var underlyingNonNullableType = isNullable ? type.UnwrapNullableType() : type;
if (!underlyingNonNullableType.GetTypeInfo().IsEnum)
{
return type;
}
var underlyingEnumType = Enum.GetUnderlyingType(underlyingNonNullableType);
return isNullable ? MakeNullable(underlyingEnumType) : underlyingEnumType;
}
19
Source : JsonMapper.cs
with MIT License
from CatLib
with MIT License
from CatLib
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
See More Examples