public static void Main() { LinkedList <string> ienumerableLinkedList = new LinkedList <string> ("First element", new LinkedList <string> ("Second element", new LinkedList <string> ("Third element"))); foreach (var element in ienumerableLinkedList) { Nullable <decimal> number = null; Console.WriteLine("LinkedList -> {0},\nNullable -> {1}", element, number.GetValueOrDefault()); } Console.WriteLine(); ValueType valType = 10; Console.WriteLine("ValueType valType = {0}, {0} is {1}", valType, valType.GetType()); valType = 6.3; Console.WriteLine("valType = {0}, {0} is {1}", valType, valType.GetType()); valType = 10000000000000000000; Console.WriteLine("valType = {0}, {0} is {1}", valType, valType.GetType()); decimal numDec = 100; valType = numDec; // boxing (stak -> heap) Console.WriteLine("decimal numDec = {0}, valType = numDec, valType is {1}", numDec, valType.GetType()); //int numInt = (int)valType; // return InvalidCastException int numInt = (int)(decimal)valType; // unboxing (heap -> stak) Console.WriteLine("int numInt = (int)(decimal)valType, numInt = {0}", numInt); }
public FieldDefinition this[ValueType enumValue] { get { if (!enumValue.GetType().IsEnum) { throw new ArgumentException($"{enumValue} is not a valid enum value.", nameof(enumValue)); } FieldDefinition fieldDefinition; if (!_definitions.TryGetValue(enumValue, out fieldDefinition)) { throw new Exception($"Enum value {enumValue} does not belong to the {EnumType.FullName} enum."); } return(fieldDefinition); } set { if (!enumValue.GetType().IsEnum) { throw new ArgumentException($"{enumValue} is not a valid enum value.", nameof(enumValue)); } if (!_definitions.ContainsKey(enumValue)) { throw new Exception($"Enum value {enumValue} does not belong to the {EnumType.FullName} enum."); } _definitions[enumValue] = value; } }
internal static NumericField SetValue(this NumericField field, ValueType value) { if (value.GetType().IsEnum) { value = (ValueType)Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType())); } if (value is int) { return(field.SetIntValue((int)value)); } if (value is long) { return(field.SetLongValue((long)value)); } if (value is double) { return(field.SetDoubleValue((double)value)); } if (value is float) { return(field.SetFloatValue((float)value)); } throw new ArgumentException("Unable to store ValueType " + value.GetType() + " as NumericField.", "value"); }
internal override void SetValue(ValueType value) { if (value.GetType() != typeof(float)) { throw new ArgumentException(string.Format("[{0}] not match [{1}]'s value.", value.GetType().Name, this.GetType().Name)); } this.Value = (float)value; }
public static void PushValue(IntPtr L, ValueType v) { if (v == null) { LuaDLL.lua_pushnil(L); return; } Type type = v.GetType(); int metaReference = LuaStatic.GetMetaReference(L, type); ObjectTranslator objectTranslator = ObjectTranslator.Get(L); if (metaReference > 0) { int index = objectTranslator.AddObject(v); LuaDLL.tolua_pushnewudata(L, metaReference, index); } else { LuaCSFunction preModule = LuaStatic.GetPreModule(L, type); if (preModule != null) { preModule(L); metaReference = LuaStatic.GetMetaReference(L, type); if (metaReference > 0) { int index2 = objectTranslator.AddObject(v); LuaDLL.tolua_pushnewudata(L, metaReference, index2); return; } } LuaDLL.lua_pushnil(L); Debugger.LogError("Type {0} not wrap to lua", LuaMisc.GetTypeName(type)); } }
public static ValueType Clone(this ValueType source) { if (source == null) { throw new ArgumentNullException("source"); } lock (ms_cloneCache) { var sourceType = source.GetType(); if (!ms_cloneCache.ContainsKey(sourceType)) { var cloneMethod = new DynamicMethod("Clone", typeof(ValueType), new Type[] { typeof(ValueType) }, true); var gen = cloneMethod.GetILGenerator(); var local = gen.DeclareLocal(sourceType); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Unbox_Any, sourceType); gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Box, sourceType); gen.Emit(OpCodes.Ret); var clone = (Func <ValueType, ValueType>)cloneMethod.CreateDelegate(typeof(Func <ValueType, ValueType>)); ms_cloneCache.Add(sourceType, clone); } return(ms_cloneCache[sourceType](source)); } }
/// <summary> /// The GetStructureBytes. /// </summary> /// <param name="structure">The structure<see cref="ValueType"/>.</param> /// <returns>The <see cref="byte[]"/>.</returns> public unsafe static byte[] GetStructureBytes(ValueType structure) { Type t = structure.GetType(); if (t.IsPrimitive || t.IsLayoutSequential) { return(extractor.ValueStructureToBytes(structure)); } byte[] b = null; var _structure = structure; if (structure is DateTime) { b = new byte[8]; _structure = ((DateTime)structure).ToBinary(); } else if (structure is Enum) { b = new byte[4]; _structure = Convert.ToInt32((Enum)structure); } else { b = new byte[Marshal.SizeOf(_structure)]; } fixed(byte *pb = b) Marshal.StructureToPtr(_structure, new IntPtr(pb), false); return(b); }
public static string GetStringValue(ValueType e) { if (e == null) { return(""); } string output = null; Type type = e.GetType(); FieldInfo fi = type.GetField(e.ToString()); if (fi == null) { return(""); } StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[]; if (attrs.Length > 0) { output = attrs[0].Value; } return(output); }
public static QsFlowingTuple FromStruct(ValueType value) { var StructType = value.GetType(); var props = StructType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); var all = from o in props where o.IsSpecialName == false && o.GetIndexParameters().Length == 0 select o; QsTupleValue[] fefe = new QsTupleValue[all.Count()]; int id = 10; // begin the properties from id == 10 like Basic auto numbering in old days for (int ix = 0; ix < all.Count(); ix++) { var StructProperty = all.ElementAt(ix); fefe[ix].Name = StructProperty.Name; fefe[ix].Id = id; if (StructProperty.PropertyType.IsValueType) { fefe[ix].SetLazyValue(StructProperty.GetValue(value, null)); } else { fefe[ix].Value = Root.NativeToQsConvert(StructProperty.GetValue(value, null)); } id += 10; } return(new QsFlowingTuple(fefe)); }
private UniformSingleVariable GetVariable(ValueType value, string varNameInShader) { Type t = value.GetType(); Type varType; if (variableDict == null) { variableDict = new Dictionary <Type, Type>(); variableDict.Add(typeof(bool), typeof(UniformBool)); variableDict.Add(typeof(float), typeof(UniformFloat)); variableDict.Add(typeof(vec2), typeof(UniformVec2)); variableDict.Add(typeof(vec3), typeof(UniformVec3)); variableDict.Add(typeof(vec4), typeof(UniformVec4)); variableDict.Add(typeof(mat2), typeof(UniformMat2)); variableDict.Add(typeof(mat3), typeof(UniformMat3)); variableDict.Add(typeof(mat4), typeof(UniformMat4)); variableDict.Add(typeof(samplerValue), typeof(UniformSampler)); } if (variableDict.TryGetValue(t, out varType)) { object variable = Activator.CreateInstance(varType, varNameInShader); return(variable as UniformSingleVariable); } else { throw new Exception(string.Format( "UniformVariable type [{0}] doesn't exists or not included in the variableDict!", t)); } }
public static bool SecurityResetMemoryContext(ValueType valueTypeObject, int size) { FieldInfo[] fInfos = valueTypeObject.GetType().GetFields(); TypeMapping mapping = new TypeMapping(); bool canResetMemory = false; if (!mapping.IsNonStructOrEnumValueType(valueTypeObject)) { foreach (FieldInfo item in fInfos) { if (item.GetType().BaseType.Name == @"System.ValueType") { canResetMemory = true; } else { canResetMemory = false; break; } } } if (canResetMemory) { ResetMemoryContext(valueTypeObject, size); } return(canResetMemory); }
public static bool TrySerializeValueType(ValueType obj, out byte[] result) { result = null; if (obj == null) { Throw.ArgumentNullException(Argument.obj); } if (CanSerializeValueType(obj.GetType(), false)) { try { result = SerializeValueType(obj); } catch (Exception e) when(!e.IsCritical()) { // CanSerializeStruct filters a sort of conditions but serialization may fail even in that case - this catch is to protect this case. return(false); } return(true); } return(false); }
unsafe public static int NumToBytes(ValueType num, byte *data, int index) { int bytesCopied = 0; string dotNetType = num.GetType().ToString(); // Learned about how to do this from looking at source of BitConverter.GetBytes() // https://referencesource.microsoft.com/#mscorlib/system/bitconverter.cs,76 byte *b = data + index; switch (dotNetType) { case "System.SByte": *(sbyte *)b = (sbyte)num; break; case "System.Byte": *b = (byte)num; break; case "System.Int16": *(short *)b = (short)num; break; case "System.UInt16": *(ushort *)b = (ushort)num; break; case "System.Int32": *(int *)b = (int)num; break; case "System.UInt32": *(uint *)b = (uint)num; break; case "System.Single": *(float *)b = (float)num; break; case "System.Double": *(double *)b = (double)num; break; } bytesCopied = SizeOf(dotNetType); return(bytesCopied); }
protected void NotifyValue(PropertyID id, ValueType value) { Debug.Assert(this.IsInitialized); Debug.Assert(value.GetType().IsValueType); Debug.Assert(!this.IsDestructed); this.World.AddChange(new PropertyValueChange(this, id, value)); }
internal static Query CreateNumericRangeQuery(string fieldName, ValueType lowerBound, ValueType upperBound, RangeType lowerRange, RangeType upperRange) { if (lowerBound == null && upperBound == null) { throw new ArgumentException("lowerBound and upperBound may not both be null."); } if (lowerBound == null) { lowerBound = (ValueType)upperBound.GetType().GetField("MinValue").GetValue(null); } else if (upperBound == null) { upperBound = (ValueType)lowerBound.GetType().GetField("MaxValue").GetValue(null); } if (lowerBound.GetType() != upperBound.GetType()) { throw new ArgumentException("Cannot compare different value types " + lowerBound.GetType() + " and " + upperBound.GetType()); } lowerBound = ToNumericFieldValue(lowerBound); upperBound = ToNumericFieldValue(upperBound); var minInclusive = lowerRange == RangeType.Inclusive; var maxInclusive = upperRange == RangeType.Inclusive; if (lowerBound is int) { return(NumericRangeQuery.NewIntRange(fieldName, (int)lowerBound, (int)upperBound, minInclusive, maxInclusive)); } if (lowerBound is long) { return(NumericRangeQuery.NewLongRange(fieldName, (long)lowerBound, (long)upperBound, minInclusive, maxInclusive)); } if (lowerBound is float) { return(NumericRangeQuery.NewFloatRange(fieldName, (float)lowerBound, (float)upperBound, minInclusive, maxInclusive)); } if (lowerBound is double) { return(NumericRangeQuery.NewDoubleRange(fieldName, (double)lowerBound, (double)upperBound, minInclusive, maxInclusive)); } throw new NotSupportedException("Unsupported numeric range type " + lowerBound.GetType()); }
private string GetBracketType(ValueType value) { string bracket = string.Empty; if (value.GetType() == typeof(char)) { bracket = StgFormat.CHAR_FORMAT; } if (value.GetType() == typeof(DateTime)) { bracket = StgFormat.STRING_FORMAT; } if (value.GetType() == typeof(string)) { bracket = StgFormat.STRING_FORMAT; } return(bracket); }
public virtual string GetName(ValueType i) { if (i.GetType() != _type) { throw new ArgumentException("Type unmatch", "i"); } return(i.ToString()); }
/// <summary> /// 格式化值类型的值 /// </summary> /// <param name="value"></param> /// <returns></returns> private static ValueType FormatValueType(ValueType value) { if (value.GetType().IsEnum) { int ret = (int)value; return(ret); } return(value); }
public JsonNumber(ValueType value) { if (!value.GetType().IsNumeric()) { throw new ArgumentException("The give value is not a primitive number data type.", "value"); } Value = value; }
internal static IDictionary <string, object> ToDictionary(ValueType value) { var dictionary = new Dictionary <string, object>(); foreach (var field in value.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { dictionary.Add(field.Name, field.GetValue(value)); } return(dictionary); }
public virtual string GetRawDescription(ValueType i) { if (i.GetType() != _type) { throw new ArgumentException("Type unmatch", "i"); } object item = _enumListItemType.GetMethod("CreateListItemWithTextID").Invoke(null, new object[] { i }); return(item.ToString()); }
public virtual bool canHandle(TypedValue value) { if (value.Type != null && !valueType.GetType().IsAssignableFrom(value.Type.GetType())) { return(false); } else { return(canWriteValue(value)); } }
internal override bool SetValue(ValueType value) { if (value.GetType() != typeof(samplerValue)) { throw new ArgumentException(string.Format("[{0}] not match [{1}]'s value.", value.GetType().Name, this.GetType().Name)); } var v = (samplerValue)value; if (v != this.value) { this.value = v; this.Updated = true; return(true); } else { return(false); } }
public override uint ConvertToBasis(ValueType totalValue) { String msg; if (totalValue is ProductVersion) { return(Convert.ToUInt32(((ProductVersion)totalValue).TotalVersion)); } msg = String.Format("Преобразование невозможно. Передан тип {0}, ожидается {1}", totalValue.GetType().ToString(), typeof(ProductVersion).ToString()); throw new InvalidCastException(msg); }
/// <summary> /// returns the first tag name of the given field /// </summary> /// <param name="valueType">An enum's member</param> /// <returns>the first tag name or an empty string, if it has no tags</returns> public static string GetFirstTagName(ValueType valueType) { foreach (var member in GetMembers(valueType.GetType())) { if (member.Value.GetValue(valueType).Equals(valueType)) { return(member.Key); } } return(""); }
public static byte[] StructToBytes(ValueType structObj) { int size = Marshal.SizeOf(structObj.GetType()); byte[] bytes = new byte[size]; IntPtr structPtr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(structObj, structPtr, false); Marshal.Copy(structPtr, bytes, 0, size); Marshal.FreeHGlobal(structPtr); return(bytes); }
/// <summary> /// 获取指定枚举的描述 /// </summary> /// <param name="vt"></param> /// <returns></returns> public static string GetDes(ValueType vt) { var list = GetList(vt.GetType()); foreach (var item in list) { if ((int)item.Key == (int)vt) { return(item.Value); } } return(string.Empty); }
public override uint ConvertToBasis(ValueType totalValue) { string msg; if (totalValue is DateTime) { return(Unix.ToUnixTime((DateTime)totalValue)); } msg = String.Format("Преобразование невозможно. Передан тип {0}, ожидается {1}", totalValue.GetType(), typeof(DateTime)); throw new InvalidCastException(msg); }
public override uint ConvertToBasis(ValueType totalValue) { String msg; if (totalValue is Byte) { return(Convert.ToUInt32(totalValue)); } msg = String.Format("ѕреобразование невозможно. ѕередан тип {0}, ожидаетс¤ {1}", totalValue.GetType(), typeof(Byte)); throw new InvalidCastException(msg); }
public override uint ConvertToBasis(ValueType totalValue) { String msg; if (totalValue is Int16) { return((UInt32)totalValue); } msg = String.Format("Преобразование невозможно. Передан тип {0}, ожидается {1}", totalValue.GetType(), typeof(UInt32)); throw new InvalidCastException(msg); }
public StructValue(ValueType obj) { type = obj.GetType(); isPrimitive = getTypeIndex(type) != TypeIndex.INVALID; this.obj = obj; }