Here are the examples of the csharp api System.Array.SetValue(object, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
528 Examples
19
View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu
License : MIT License
Project Creator : 0blu
private static Array DeserializeArray(Protocol16Stream input)
{
short size = DeserializeShort(input);
byte typeCode = (byte)input.ReadByte();
switch ((Protocol16Type)typeCode)
{
case Protocol16Type.Array:
{
Array array = DeserializeArray(input);
Type arrayType = array.GetType();
Array result = Array.CreateInstance(arrayType, size);
result.SetValue(array, 0);
for (short i = 1; i < size; i++)
{
array = DeserializeArray(input);
result.SetValue(array, i);
}
return result;
}
case Protocol16Type.ByteArray:
{
byte[][] array = new byte[size][];
for (short i = 0; i < size; i++)
{
array[i] = DeserializeByteArray(input);
}
return array;
}
case Protocol16Type.Dictionary:
{
DeserializeDictionaryArray(input, size, out Array result);
return result;
}
default:
{
Type arrayType = GetTypeOfCode(typeCode);
Array result = Array.CreateInstance(arrayType, size);
for (short i = 0; i < size; i++)
{
result.SetValue(Deserialize(input, typeCode), i);
}
return result;
}
}
}
19
View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu
License : MIT License
Project Creator : 0blu
private static bool DeserializeDictionaryArray(Protocol16Stream input, short size, out Array result)
{
Type type = DeserializeDictionaryType(input, out byte keyTypeCode, out byte valueTypeCode);
result = Array.CreateInstance(type, size);
for (short i = 0; i < size; i++)
{
if (!(Activator.CreateInstance(type) is IDictionary dictionary))
{
return false;
}
short arraySize = DeserializeShort(input);
for (int j = 0; j < arraySize; j++)
{
object key;
if (keyTypeCode > 0)
{
key = Deserialize(input, keyTypeCode);
}
else
{
byte nextKeyTypeCode = (byte)input.ReadByte();
key = Deserialize(input, nextKeyTypeCode);
}
object value;
if (valueTypeCode > 0)
{
value = Deserialize(input, valueTypeCode);
}
else
{
byte nextValueTypeCode = (byte)input.ReadByte();
value = Deserialize(input, nextValueTypeCode);
}
dictionary.Add(key, value);
}
result.SetValue(dictionary, i);
}
return true;
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d= BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 40);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
string n = RandomHelper.RandomValue<string>(false);
while(dt.Columns.Contains(n))
n = RandomHelper.RandomValue<string>(false);
dt.Columns.Add(n, typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
{
if (t.IsPrimitive)
{
if (t == typeof(byte))
{
return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
}
if (t == typeof(sbyte))
{
return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
}
if (t == typeof(short))
{
return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
}
if (t == typeof(ushort))
{
return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
}
if (t == typeof(int))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
if (t == typeof(uint))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
if (t == typeof(long))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToInt64(bytes, 0);
}
if (t == typeof(ulong))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
if (t == typeof(float))
{
var bytes = new byte[4];
Rand.NextBytes(bytes);
var f = BitConverter.ToSingle(bytes, 0);
if (float.IsNaN(f))
f = (float)RandomValue<short>();
return f;
}
if (t == typeof(double))
{
var bytes = new byte[8];
Rand.NextBytes(bytes);
var d = BitConverter.ToDouble(bytes, 0);
if (double.IsNaN(d))
d = (double)RandomValue<short>();
return d;
}
if (t == typeof(char))
{
var roll = Rand.Next(ASCII.Length);
return ASCII[roll];
}
if (t == typeof(bool))
{
return (Rand.Next(2) == 1);
}
throw new InvalidOperationException();
}
if (t == typeof(decimal))
{
return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
}
if (t == typeof(string))
{
int start = stringValueAllowEmpty ? 0 : 1;
var len = Rand.Next(start, 28);
var c = new char[len];
for (var i = 0; i < c.Length; i++)
{
c[i] = (char)typeof(char).RandomValue();
}
return new string(c);
}
if (t == typeof(DateTime))
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var bytes = new byte[4];
Rand.NextBytes(bytes);
var secsOffset = BitConverter.ToInt32(bytes, 0);
var retDate = epoch.AddSeconds(secsOffset);
return retDate;
}
if (t == typeof(TimeSpan))
{
return new TimeSpan(RandomValue<DateTime>().Ticks);
}
if (t == typeof(DataTable))
{
DataTable dt = new DataTable();
int coluCount = Rand.Next(10, 30);
for (int i = 0; i < coluCount; i++)
{
dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
}
int rowCount = Rand.Next(20, 50);
for (int i = 0; i < rowCount; i++)
{
var row = new object[coluCount];
for (int zi = 0; zi < coluCount; zi++)
{
row[zi] = RandomHelper.RandomValue<object>();
}
dt.Rows.Add(row);
}
return dt;
}
if (t.IsNullable())
{
// leave it unset
if (Rand.Next(2) == 0)
{
// null!
return Activator.CreateInstance(t);
}
var underlying = Nullable.GetUnderlyingType(t);
var val = underlying.RandomValue(stringValueAllowEmpty);
var cons = t.GetConstructor(new[] { underlying });
return cons.Invoke(new object[] { val });
}
if (t.IsEnum)
{
var allValues = Enum.GetValues(t);
var ix = Rand.Next(allValues.Length);
return allValues.GetValue(ix);
}
if (t.IsArray)
{
var valType = t.GetElementType();
var len = Rand.Next(20, 50);
var ret = Array.CreateInstance(valType, len);
//var add = t.GetMethod("SetValue");
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
ret.SetValue(elem, i);
}
return ret;
}
if (t.IsGenericType)
{
var defind = t.GetGenericTypeDefinition();
if (defind == typeof(HashSet<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("Contains");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(Dictionary<,>))
{
var keyType = t.GetGenericArguments()[0];
var valType = t.GetGenericArguments()[1];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var contains = t.GetMethod("ContainsKey");
var len = Rand.Next(20, 50);
if (keyType == typeof(Boolean))
len = 2;
for (var i = 0; i < len; i++)
{
var val = valType.RandomValue(stringValueAllowEmpty);
var key = keyType.RandomValue(stringValueAllowEmpty);
while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
key = keyType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { key, val });
}
return ret;
}
if (defind == typeof(List<>))
{
var valType = t.GetGenericArguments()[0];
var ret = Activator.CreateInstance(t);
var add = t.GetMethod("Add");
var len = Rand.Next(20, 50);
for (var i = 0; i < len; i++)
{
var elem = valType.RandomValue(stringValueAllowEmpty);
add.Invoke(ret, new object[] { elem });
}
return ret;
}
if (defind == typeof(ArraySegment<>))
{
var valType = t.GetGenericArguments()[0];
var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
var lenT = ary.GetType().GetProperty("Length");
var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
var len = (int)lenT.GetValue(ary) - offset;
return Activator.CreateInstance(t, ary, offset, len);
}
}
if (t == typeof(Guid))
return Guid.NewGuid();
if (t == typeof(object))
{
var code = Rand.Next(0, 9);
switch (code)
{
case 0:
return RandomValue<int>();
case 1:
return RandomValue<long>();
case 2:
return RandomValue<Char>();
case 3:
return RandomValue<DateTime>();
case 4:
return RandomValue<string>(stringValueAllowEmpty);
case 5:
return RandomValue<Guid>();
case 6:
return RandomValue<decimal>();
case 7:
return RandomValue<double>();
case 8:
return RandomValue<float>();
default:
return RandomValue<short>();
}
}
//model
var retObj = Activator.CreateInstance(t);
foreach (var p in t.GetFields())
{
//if (Rand.Next(5) == 0) continue;
var fieldType = p.FieldType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
foreach (var p in t.GetProperties())
{
//if (Rand.Next(5) == 0) continue;
if (p.CanWrite && p.CanRead)
{
var fieldType = p.PropertyType;
p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
}
}
return retObj;
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static object FromObject(this Type targetType, object value, Encoding encoding = null)
{
if (targetType == typeof(object)) return value;
if (encoding == null) encoding = Encoding.UTF8;
var valueIsNull = value == null;
var valueType = valueIsNull ? typeof(string) : value.GetType();
if (valueType == targetType) return value;
if (valueType == typeof(byte[])) //byte[] -> guid
{
if (targetType == typeof(Guid))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
if (targetType == typeof(Guid?))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
}
}
if (targetType == typeof(byte[])) //guid -> byte[]
{
if (valueIsNull) return null;
if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
var bytes = new byte[16];
var guidN = ((Guid)value).ToString("N");
for (var a = 0; a < guidN.Length; a += 2)
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
return bytes;
}
return encoding.GetBytes(value.ToInvariantCultureToString());
}
else if (targetType.IsArray)
{
if (value is Array valueArr)
{
var targetElementType = targetType.GetElementType();
var sourceArrLen = valueArr.Length;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
return target;
}
//if (value is IList valueList)
//{
// var targetElementType = targetType.GetElementType();
// var sourceArrLen = valueList.Count;
// var target = Array.CreateInstance(targetElementType, sourceArrLen);
// for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
// return target;
//}
}
var func = _dicFromObject.GetOrAdd(targetType, tt =>
{
if (tt == typeof(object)) return vs => vs;
if (tt == typeof(string)) return vs => vs;
if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
if (tt == typeof(bool)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
}
return false;
};
if (tt == typeof(bool?)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
case "false":
case "0":
return false;
}
return null;
};
if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
if (tt.NullableTypeOrThis().IsEnum)
{
var tttype = tt.NullableTypeOrThis();
var ttdefval = tt.CreateInstanceGetDefaultValue();
return vs =>
{
if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
return Enum.Parse(tttype, vs, true);
};
}
var localTargetType = targetType;
var localValueType = valueType;
return vs =>
{
if (vs == null) return null;
throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
};
});
var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
return func(valueStr);
}
19
View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
//ILRuntime doesn't support nullable valuetype
Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
Type value_type = inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClreplaced || underlying_type != null) {
return null;
}
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();
var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;
if (vt.IsreplacedignableFrom(json_type))
return reader.Value;
if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
{
if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
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 (
vt)) {
ImporterFunc importer =
custom_importers_table[json_type][vt];
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 (
vt)) {
ImporterFunc importer =
base_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe it's an enum
if (vt.IsEnum)
return Enum.ToObject (vt, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (vt, 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;
var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
{
item = (int) item;
}
else
{
item = rt.CheckCLRTypes(item);
}
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];
if (value_type is ILRuntime.Reflection.ILRuntimeType)
instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
else
instance = Activator.CreateInstance(value_type);
bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
while (true)
{
reader.Read();
if (reader.Token == JsonToken.ObjectEnd)
break;
string key = (string) reader.Value;
if (t_data.Properties.ContainsKey(key))
{
PropertyMetadata prop_data =
t_data.Properties[key];
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, key));
}
else
{
ReadSkip(reader);
continue;
}
}
var dict = ((IDictionary) instance);
var elem_type = t_data.ElementType;
object readValue = ReadValue(elem_type, reader);
var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
: t_data.ElementType;
//value 是枚举的情况没处理,毕竟少
if (isIntKey)
{
var dictValueType = value_type.GetGenericArguments()[1];
IConvertible convertible = dictValueType as IConvertible;
if (convertible == null)
{
//自定义类型扩展
if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
{
var v = Convert.ChangeType(readValue.ToString(), dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(Convert.ToInt32(key), readValue);
// throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
}
}
else
{
var v = Convert.ChangeType(readValue, dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(key, readValue);
}
}
}
}
return instance;
}
19
View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
internal static object ParseValue(Type type, string json) {
if (type == typeof(string)) {
if (json.Length <= 2)
return string.Empty;
string str = json.Substring(1, json.Length - 2);
return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
}
if (type == typeof(int)) {
int result;
int.TryParse(json, out result);
return result;
}
if (type == typeof(float)) {
float result;
float.TryParse(json, out result);
return result;
}
if (type == typeof(double)) {
double result;
double.TryParse(json, out result);
return result;
}
if (type == typeof(bool)) {
return json.ToLower() == "true";
}
if (json == "null") {
return null;
}
if (type.IsArray) {
Type arrayType = type.GetElementType();
if (json[0] != '[' || json[json.Length - 1] != ']')
return null;
List<string> elems = Split(json);
Array newArray = Array.CreateInstance(arrayType, elems.Count);
for (int i = 0; i < elems.Count; i++)
newArray.SetValue(ParseValue(arrayType, elems[i]), i);
splitArrayPool.Push(elems);
return newArray;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
Type listType = type.GetGenericArguments()[0];
if (json[0] != '[' || json[json.Length - 1] != ']')
return null;
List<string> elems = Split(json);
var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
for (int i = 0; i < elems.Count; i++)
list.Add(ParseValue(listType, elems[i]));
splitArrayPool.Push(elems);
return list;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
Type keyType, valueType;
{
Type[] args = type.GetGenericArguments();
keyType = args[0];
valueType = args[1];
}
//Refuse to parse dictionary keys that aren't of type string
if (keyType != typeof(string))
return null;
//Must be a valid dictionary element
if (json[0] != '{' || json[json.Length - 1] != '}')
return null;
//The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
List<string> elems = Split(json);
if (elems.Count % 2 != 0)
return null;
var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
for (int i = 0; i < elems.Count; i += 2) {
if (elems[i].Length <= 2)
continue;
string keyValue = elems[i].Substring(1, elems[i].Length - 2);
object val = ParseValue(valueType, elems[i + 1]);
dictionary.Add(keyValue, val);
}
return dictionary;
}
if (type == typeof(object)) {
return ParseAnonymousValue(json);
}
if (json[0] == '{' && json[json.Length - 1] == '}') {
return ParseObject(type, json);
}
return null;
}
19
View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static object GetValue(this TypedConstant typedConstant)
{
switch (typedConstant.Kind)
{
case TypedConstantKind.Type:
return ((ITypeSymbol)typedConstant.Value).GetCorrespondingType();
case TypedConstantKind.Primitive:
case TypedConstantKind.Enum:
return typedConstant.Value;
case TypedConstantKind.Array:
break;
default:
throw new ArgumentOutOfRangeException();
}
ImmutableArray<TypedConstant> elements = typedConstant.Values;
Array array = Array.CreateInstance(typedConstant.Type.GetCorrespondingType().GetElementType(), elements.Length);
for (int i = 0; i < elements.Length; i++)
{
array.SetValue(elements[i].GetValue(), i);
}
return array;
}
19
View Source File : CommonUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
static string Process(object obj, int level, string prefLine, Dictionary<object, int> forParentLink, HashSet<string> excludeTypes)
{
try
{
if (obj == null) return "";
Type type = obj.GetType();
if (excludeTypes.Contains(type.Name)) return "<skip>";
if (type == typeof(DateTime))
{
return ((DateTime)obj).ToString("g");
}
else if (type.IsValueType || type == typeof(string))
{
return obj.ToString();
}
else if (type.IsArray || obj is IEnumerable)
{
string elementType = null;
Array array = null;
if (type.IsArray)
{
var tt = Type.GetType(type.FullName.Replace("[]", string.Empty));
if (tt != null)
{
elementType = tt.ToString();
if (excludeTypes.Contains(tt.Name)) return "<skips>";
}
//else return "<EEEEEEE" + type.FullName;
array = obj as Array;
}
else
{
//как лучше узнать кол-во и тип?
int cnt = 0;
foreach (var o in obj as IEnumerable) cnt++;
array = Array.CreateInstance(typeof(object), cnt);
int i = 0;
foreach (var o in obj as IEnumerable)
{
if (elementType == null && o != null)
{
var tt = o.GetType();
if (excludeTypes.Contains(tt.Name)) return "<skips>";
elementType = tt.ToString();
}
array.SetValue(o, i++);
}
}
if (elementType == null) elementType = "Object";
if (excludeTypes.Contains(elementType)) return "<skips>";
var info = "<" + elementType + "[" + array.Length.ToString() + "]" + ">";
if (level == 0)
{
return info + "[...]";
}
if (array.Length > 0)
{
var ress = new string[array.Length];
var resl = 0;
for (int i = 0; i < array.Length; i++)
{
ress[i] = Process(array.GetValue(i), level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
resl += ress[i].Length;
}
if (resl < LineLength)
{
var res = info + "[" + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", " + ress[i];
}
return res + "]";
}
else
{
var res = info + "["
+ Environment.NewLine + prefLine + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", "
+ Environment.NewLine + prefLine + ress[i];
}
return res + Environment.NewLine + prefLine + "]";
}
}
return info + "[]";
}
else if (obj is Type) return "<Type>" + obj.ToString();
else if (type.IsClreplaced)
{
var info = "<" + type.Name + ">";
if (forParentLink.ContainsKey(obj))
{
if (forParentLink[obj] >= level)
return info + "{duplicate}";
else
forParentLink[obj] = level;
}
else
forParentLink.Add(obj, level);
if (level == 0)
{
return info + "{...}";
}
FieldInfo[] fields = type.GetFields(BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
if (fields.Length > 0)
{
var ress = new string[fields.Length];
var resl = 0;
for (int i = 0; i < fields.Length; i++)
{
object fieldValue = fields[i].GetValue(obj);
ress[i] = fieldValue == null
? fields[i].Name + ": null"
: fields[i].Name + ": " + Process(fieldValue, level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
resl += ress[i].Length;
}
if (resl < LineLength)
{
var res = info + "{" + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", " + ress[i];
}
return res + "}";
}
else
{
var res = info + "{"
+ Environment.NewLine + prefLine + ress[0];
for (int i = 1; i < ress.Length; i++)
{
res += ", "
+ Environment.NewLine + prefLine + ress[i];
}
return res + Environment.NewLine + prefLine + "}";
}
}
return info + "{}";
}
else
throw new ArgumentException("Unknown type");
}
catch
{
return "<exception>";
}
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : ahydrax
License : MIT License
Project Creator : ahydrax
private static object CreateSampleInstanceInternal(this Type type, int currentDepth, int maxDepth)
{
if (currentDepth > maxDepth) return GetDefaultValue(type);
var instance = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
var propertyType = property.PropertyType;
if (propertyType.CanBeInstantiated())
{
type.GetProperty(property.Name).SetValue(instance,
propertyType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth));
}
if (typeof(IEnumerable).IsreplacedignableFrom(propertyType)
&& propertyType != typeof(string))
{
var elementType = propertyType.IsArray
? propertyType.GetElementType()
: propertyType.GenericTypeArguments[0];
var array = Array.CreateInstance(elementType, 1);
array.SetValue(
elementType.CanBeInstantiated()
? elementType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth)
: GetDefaultValue(elementType),
0);
type.GetProperty(property.Name).SetValue(instance, array);
}
}
return instance;
}
19
View Source File : CharSpanLookupDictionary.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array is KeyValuePair<string, TValue>[] tarray)
{
(this as ICollection<KeyValuePair<string, TValue>>).CopyTo(tarray, arrayIndex);
return;
}
if (!(array is object[]))
throw new ArgumentException($"Array needs to be an instance of {typeof(TValue[])} or object[].");
var i = arrayIndex;
foreach (var (k, v) in this.InternalBuckets)
{
var kdv = v;
while (kdv != null)
{
array.SetValue(new KeyValuePair<string, TValue>(kdv.Key, kdv.Value), i++);
kdv = kdv.Next;
}
}
}
19
View Source File : DynamicUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static object CreateSharpArgumentInfoArray(params int[] values)
{
Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName);
Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName);
Array a = Array.CreateInstance(csharpArgumentInfoType, values.Length);
for (int i = 0; i < values.Length; i++)
{
MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) });
object arg = createArgumentInfoMethod.Invoke(null, new object[] { 0, null });
a.SetValue(arg, i);
}
return a;
}
19
View Source File : JSON.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private object CreateArray(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
{
if (bt == null)
bt = typeof(object);
Array col = Array.CreateInstance(bt, data.Count);
var arraytype = bt.GetElementType();
// create an array of objects
for (int i = 0; i < data.Count; i++)
{
object ob = data[i];
if (ob == null)
{
continue;
}
if (ob is IDictionary)
col.SetValue(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt, null), i);
else if (ob is ICollection)
col.SetValue(CreateArray((List<object>)ob, bt, arraytype, globalTypes), i);
else
col.SetValue(ChangeType(ob, bt), i);
}
return col;
}
19
View Source File : DataColumnAppender.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public DataColumn ToDataColumn()
{
Array data = Array.CreateInstance(_dataField.ClrNullableIfHasNullsType, _values.Count);
for(int i = 0; i < _values.Count; i++)
{
data.SetValue(_values[i], i);
}
return new DataColumn(_dataField, data, _isRepeated ? _rls.ToArray() : null);
}
19
View Source File : LazyColumnEnumerator.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public Array ToDataArray()
{
Array result = Array.CreateInstance(_dc.Field.ClrNullableIfHasNullsType, _count);
int i = 0;
Reset();
while(MoveNext())
{
result.SetValue(Current, i++);
}
return result;
}
19
View Source File : TreeList.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
public object ValuesAs(Type clrType)
{
Array cellArray = Array.CreateInstance(clrType, _values.Count);
for (int i = 0; i < _values.Count; i++)
{
cellArray.SetValue(_values[i], i);
}
return cellArray;
}
19
View Source File : TestBase.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
protected object WriteReadSingle(DataField field, object value, CompressionMethod compressionMethod = CompressionMethod.None, int compressionLevel = -1)
{
//for sanity, use disconnected streams
byte[] data;
using (var ms = new MemoryStream())
{
// write single value
using (var writer = new ParquetWriter(new Schema(field), ms))
{
writer.CompressionMethod = compressionMethod;
writer.CompressionLevel = compressionLevel;
using (ParquetRowGroupWriter rg = writer.CreateRowGroup())
{
Array dataArray = Array.CreateInstance(field.ClrNullableIfHasNullsType, 1);
dataArray.SetValue(value, 0);
var column = new DataColumn(field, dataArray);
rg.WriteColumn(column);
}
}
data = ms.ToArray();
}
using (var ms = new MemoryStream(data))
{
// read back single value
ms.Position = 0;
using (var reader = new ParquetReader(ms))
{
using (ParquetRowGroupReader rowGroupReader = reader.OpenRowGroupReader(0))
{
DataColumn column = rowGroupReader.ReadColumn(field);
return column.Data.GetValue(0);
}
}
}
}
19
View Source File : ArrayMarshaler.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
public object DemarshalObject(Stream stream)
{
int count = Int32Marshaler.Demarshal(stream);
Type elementType = _elementMarshaler.ManagedType;
Array array = Array.CreateInstance(elementType, count);
for (int i = 0; i < count; i++)
{
object element = _elementMarshaler.DemarshalObject(stream);
array.SetValue(element, i);
}
return array;
}
19
View Source File : ObjectGenerator.cs
License : GNU General Public License v3.0
Project Creator : andysal
License : GNU General Public License v3.0
Project Creator : andysal
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
19
View Source File : JsonMapper.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : 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
View Source File : EntityExtensions.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
private static object ToDataArray(Array array, HashSet<object> visited)
{
var dataArray = Array.CreateInstance(array.GetType().GetElementType(), array.GetLength(0));
for (int i = 0; i < dataArray.GetLength(0); i++)
{
dataArray.SetValue(ToData(array.GetValue(i), visited), i);
}
return dataArray;
}
19
View Source File : RealBinaryMapping.Read.cs
License : Apache License 2.0
Project Creator : AntonioDePau
License : Apache License 2.0
Project Creator : 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
View Source File : ArrayFieldAddOperation.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
void IUndoRedo.Do()
{
var itemType = _arr.GetType().GetElementType();
var addCount = (_relatedAdds != null) ? _relatedAdds.Count + 1 : 1;
var tmp = Array.CreateInstance(itemType, _arr.Length + addCount);
Array.Copy(_arr, 0, tmp, 0, _arr.Length);
var idx = _arr.Length;
tmp.SetValue(_value, idx++);
if (_relatedAdds != null)
{
for (int i = 0; i < addCount - 1; i++)
{
var val = _relatedAdds[i]._value;
tmp.SetValue(val, idx + i);
}
}
_arr = tmp;
_setter(tmp);
}
19
View Source File : ArrayField.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
protected override void DoAdd(object item, AIInspectorState state)
{
var arr = (Array)_list;
var tmp = Array.CreateInstance(_itemType, arr.Length + 1);
Array.Copy(arr, 0, tmp, 0, arr.Length);
tmp.SetValue(item, arr.Length);
_setter(tmp);
state.currentAIUI.undoRedo.Do(new ArrayFieldAddOperation(tmp, _setter, item));
}
19
View Source File : ArrayFieldRemoveOperation.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
void IUndoRedo.Undo()
{
var itemType = _arr.GetType().GetElementType();
var tmp = Array.CreateInstance(itemType, _arr.Length + 1);
Array.Copy(_arr, 0, tmp, 0, _index);
if (_index < _arr.Length)
{
Array.Copy(_arr, _index, tmp, _index + 1, _arr.Length - _index);
}
tmp.SetValue(_value, _index);
_arr = tmp;
_setter(tmp);
}
19
View Source File : ComplexTypeReflector.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public object? CreateValue(object value)
{
if (value == null)
return null;
if (value is IEnumerable enumerable)
return CreateValue(enumerable);
switch (ComplexTypeCode)
{
case ComplexTypeCode.Array:
case ComplexTypeCode.IEnumerable:
var a = Array.CreateInstance(ItemType, 1);
a.SetValue(value, 0);
return a;
case ComplexTypeCode.ICollection:
var c = Activator.CreateInstance(PropertyInfo.PropertyType);
AddMethod!.Invoke(c, new object[] { value });
return c;
case ComplexTypeCode.IDictionary:
return value;
}
return null;
}
19
View Source File : JsonMapper.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
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 (inst_type.IsClreplaced || underlying_type != null) {
return null;
}
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 (value_type.IsEnum)
return Enum.ToObject (value_type, reader.Value);
// 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));
} else {
ReadSkip (reader);
continue;
}
}
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
19
View Source File : SortedList.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public virtual void CopyTo (Array array, int arrayIndex)
{
if (null == array)
throw new ArgumentNullException();
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (array.Rank > 1)
throw new ArgumentException("array is multi-dimensional");
if (arrayIndex >= array.Length)
throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
IDictionaryEnumerator it = GetEnumerator ();
int i = arrayIndex;
while (it.MoveNext ()) {
array.SetValue (it.Entry, i++);
}
}
19
View Source File : SortedList.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
private void CopyToArray (Array arr, int i,
EnumeratorMode mode)
{
if (arr == null)
throw new ArgumentNullException ("arr");
if (i < 0 || i + this.Count > arr.Length)
throw new ArgumentOutOfRangeException ("i");
IEnumerator it = new Enumerator (this, mode);
while (it.MoveNext ()) {
arr.SetValue (it.Current, i++);
}
}
19
View Source File : SortedList~2.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
void ICollection.CopyTo (Array array, int arrayIndex)
{
if (null == array)
throw new ArgumentNullException();
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (array.Rank > 1)
throw new ArgumentException("array is multi-dimensional");
if (arrayIndex >= array.Length)
throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
IEnumerator<KeyValuePair<TKey,TValue>> it = GetEnumerator ();
int i = arrayIndex;
while (it.MoveNext ()) {
array.SetValue (it.Current, i++);
}
}
19
View Source File : System.Collections.ArrayList.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public override void CopyTo(int index, Array array, int arrayIndex, int count)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", "Can't be less than zero.");
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException("arrayIndex", "Can't be less than zero.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("index", "Can't be less than zero.");
}
if (index >= m_Adaptee.Count)
{
throw new ArgumentException("Can't be more or equal to list count.", "index");
}
if (array.Rank > 1)
{
throw new ArgumentException("Can't copy into multi-dimensional array.");
}
if (arrayIndex >= array.Length)
{
throw new ArgumentException("arrayIndex can't be greater than array.Length - 1.");
}
if (array.Length - arrayIndex + 1 < count)
{
throw new ArgumentException("Destination array is too small.");
}
// re-ordered to avoid possible integer overflow
if (index > m_Adaptee.Count - count)
{
throw new ArgumentException("Index and count do not denote a valid range of elements.", "index");
}
for (var i = 0; i < count; i++)
{
array.SetValue(m_Adaptee[index + i], arrayIndex + i);
}
}
19
View Source File : ExpressionInterpreter.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
void VisitNewArrayInit (NewArrayExpression newArray)
{
var array = Array.CreateInstance (
newArray.Type.GetElementType (),
newArray.Expressions.Count);
for (int i = 0; i < array.Length; i++) {
Visit (newArray.Expressions [i]);
array.SetValue (Pop (), i);
}
Push (array);
}
19
View Source File : Hashtable.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
private void CopyToArray (Array arr, int i,
EnumeratorMode mode)
{
IEnumerator it = new Enumerator (this, mode);
while (it.MoveNext ()) {
arr.SetValue (it.Current, i++);
}
}
19
View Source File : System.Collections.Generic.SortedList.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (null == array)
throw new ArgumentNullException();
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (array.Rank > 1)
throw new ArgumentException("array is multi-dimensional");
if (arrayIndex >= array.Length)
throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
var it = GetEnumerator();
var i = arrayIndex;
while (it.MoveNext())
{
array.SetValue(it.Current, i++);
}
}
19
View Source File : System.Collections.Generic.SortedList.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
private void CopyToArray(Array arr, int i, EnumeratorMode mode)
{
if (arr == null)
throw new ArgumentNullException("arr");
if (i < 0 || i + Count > arr.Length)
throw new ArgumentOutOfRangeException("i");
IEnumerator it = new Enumerator(this, mode);
while (it.MoveNext())
{
arr.SetValue(it.Current, i++);
}
}
19
View Source File : System.Collections.Hashtable.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public virtual void CopyTo(Array array, int arrayIndex)
{
if (null == array)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex");
if (array.Rank > 1)
throw new ArgumentException("array is multidimensional");
if ((array.Length > 0) && (arrayIndex >= array.Length))
throw new ArgumentException("arrayIndex is equal to or greater than array.Length");
if (arrayIndex + this.inUse > array.Length)
throw new ArgumentException("Not enough room from arrayIndex to end of array for this Hashtable");
IDictionaryEnumerator it = GetEnumerator();
int i = arrayIndex;
while (it.MoveNext())
{
array.SetValue(it.Entry, i++);
}
}
19
View Source File : System.Collections.Hashtable.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
private void CopyToArray(Array arr, int i,
EnumeratorMode mode)
{
IEnumerator it = new Enumerator(this, mode);
while (it.MoveNext())
{
arr.SetValue(it.Current, i++);
}
}
19
View Source File : System.Collections.SortedList.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public virtual void CopyTo(Array array, int arrayIndex)
{
if (null == array)
throw new ArgumentNullException();
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if (array.Rank > 1)
throw new ArgumentException("array is multi-dimensional");
if (arrayIndex >= array.Length)
throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
if (Count > (array.Length - arrayIndex))
throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
var it = GetEnumerator();
var i = arrayIndex;
while (it.MoveNext())
{
array.SetValue(it.Entry, i++);
}
}
19
View Source File : Hashtable.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public virtual void CopyTo (Array array, int arrayIndex)
{
if (null == array)
throw new ArgumentNullException ("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException ("arrayIndex");
if (array.Rank > 1)
throw new ArgumentException ("array is multidimensional");
if ((array.Length > 0) && (arrayIndex >= array.Length))
throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
if (arrayIndex + this.inUse > array.Length)
throw new ArgumentException ("Not enough room from arrayIndex to end of array for this Hashtable");
IDictionaryEnumerator it = GetEnumerator ();
int i = arrayIndex;
while (it.MoveNext ()) {
array.SetValue (it.Entry, i++);
}
}
19
View Source File : DataDocConverter.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
protected virtual bool TryConvertBSONtoCLR(Type target, BSONElement element, string targetName, out object clrValue, Func<BSONDoreplacedent, BSONElement, bool> filter)
{
if (element==null || element is BSONNullElement)
{
clrValue = null;
return true;
}
if (target == typeof(object))
{
//just unwrap Bson:CLR = 1:1, without type conversion
clrValue = DirectConvertBSONValue( element, filter );
return true;
}
clrValue = null;
if (target.IsSubclreplacedOf(typeof(TypedDoc)))
{
var bsonDoreplacedentElement = element as BSONDoreplacedentElement;
var doc = bsonDoreplacedentElement != null ? bsonDoreplacedentElement.Value : null;
if (doc==null) return false;//not doreplacedent
var tr = (TypedDoc)Activator.CreateInstance(target);
BSONDoreplacedentToDataDoc(doc, tr, targetName, filter: filter);
clrValue = tr;
return true;
}
//ARRAY
if (target.IsArray &&
target.GetArrayRank()==1 &&
target!=typeof(byte[]))//exclude byte[] as it is treated with m_BSONtoCLR
{
var bsonArrayElement = element as BSONArrayElement;
var arr = bsonArrayElement != null ? bsonArrayElement.Value : null;
if (arr==null) return false;//not array
var telm = target.GetElementType();
var clrArray = Array.CreateInstance(telm, arr.Length);
for(var i=0; i<arr.Length; i++)
{
object clrElement;
if (!TryConvertBSONtoCLR(telm, arr[i], targetName, out clrElement, filter))
{
return false;//could not convert some element of array
}
clrArray.SetValue(clrElement, i);
}
clrValue = clrArray;
return true;
}
//LIST<T>
if (target.IsGenericType && target.GetGenericTypeDefinition() == typeof(List<>))
{
var bsonArrayElement = element as BSONArrayElement;
var arr = bsonArrayElement != null ? bsonArrayElement.Value : null;
if (arr==null) return false;//not array
var gargs = target.GetGenericArguments();
var telm = gargs[0];
var clrList = Activator.CreateInstance(target) as System.Collections.IList;
for(var i=0; i<arr.Length; i++)
{
object clrElement;
if (!TryConvertBSONtoCLR(telm, arr[i], targetName, out clrElement, filter))
{
return false;//could not convert some element of array into element of List<t>
}
clrList.Add( clrElement );
}
clrValue = clrList;
return true;
}
//JSONDataMap
if (target==typeof(JsonDataMap))
{
var bsonDoreplacedentElement = element as BSONDoreplacedentElement;
var doc = bsonDoreplacedentElement != null ? bsonDoreplacedentElement.Value : null;
clrValue = BSONDoreplacedentToJSONMap(doc, filter);
return true;
}
if (target.IsEnum)
{
try
{
clrValue = Enum.Parse(target, ((BSONStringElement)element).Value, true);
return true;
}
catch
{
return false;
}
}
//Primitive type-targeted value
Func<BSONElement, object> func;
if (m_BSONtoCLR.TryGetValue(target, out func))
{
try
{
clrValue = func(element);
}
catch(Exception error)
{
Debug.Fail("Error in BSONRowConverter.TryConvertBSONtoCLR(): " + error.ToMessageWithType());
return false;//functor could not convert
}
return true;
}
return false;//could not convert
}
19
View Source File : JsonReader.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private static object cast(object v, Type toType, bool fromUI, DocReadOptions options, JsonHandlerAttribute fieldCustomHandler = null)
{
//See #264 - the collection inability to cast has no amorphous data so it MUST throw
//used only for collections inner calls
if (v==null) return null;
var customHandler = fieldCustomHandler ?? JsonHandlerAttribute.TryFind(toType);
if (customHandler != null)
{
var castResult = customHandler.TypeCastOnRead(v, toType, fromUI, options);
if (castResult.Outcome >= JsonHandlerAttribute.TypeCastOutcome.ChangedTargetType) toType = castResult.ToType;
if (castResult.Outcome == JsonHandlerAttribute.TypeCastOutcome.ChangedSourceValue) v = castResult.Value;
else if (castResult.Outcome == JsonHandlerAttribute.TypeCastOutcome.HandledCast) return castResult.Value;
}
//object goes as is
if (toType == typeof(object)) return v;
//IJSONDataObject
if (toType == typeof(IJsonDataObject))
{
if (v is IJsonDataObject) return v;//goes as is
if (v is string s)//string containing embedded JSON
{
var jo = s.JsonToDataObject();
return jo;
}
}
//IJSONDataMap
if (toType == typeof(JsonDataMap))
{
if (v is JsonDataMap) return v;//goes as is
if (v is string s)//string containing embedded JSON
{
var jo = s.JsonToDataObject() as JsonDataMap;
return jo;
}
}
//IJSONDataArray
if (toType == typeof(JsonDataArray))
{
if (v is JsonDataArray) return v;//goes as is
if (v is string s)//string containing embedded JSON
{
var jo = s.JsonToDataObject() as JsonDataArray;
return jo;
}
}
var nntp = toType;
if (nntp.IsGenericType && nntp.GetGenericTypeDefinition() == typeof(Nullable<>))
nntp = toType.GetGenericArguments()[0];
//20191217 DKh
if (nntp==typeof(DateTime))
{
if (options.LocalDates)
{
var d = v.AsDateTime(System.Globalization.DateTimeStyles.replacedumeLocal);
return d;
}
else //UTC (the default)
{
var d = v.AsDateTime(System.Globalization.DateTimeStyles.replacedumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal);
return d;
}
}
//20191217 DKh
//Custom JSON Readable (including config)
if (typeof(IJsonReadable).IsreplacedignableFrom(nntp) || typeof(IConfigSectionNode).IsreplacedignableFrom(nntp))
{
var toAllocate = nntp;
//Configuration requires special handling because nodes do not exist as independent enreplacedies and there
//is master/detail relationship between them
if (toAllocate == typeof(Configuration) ||
toAllocate == typeof(ConfigSectionNode) ||
toAllocate == typeof(IConfigSectionNode)) toAllocate = typeof(MemoryConfiguration);
if (toAllocate.IsAbstract)
throw new JSONDeserializationException(StringConsts.JSON_DESERIALIZATION_ABSTRACT_TYPE_ERROR.Args(toAllocate.Name, nameof(JsonHandlerAttribute)));
var newval = SerializationUtils.MakeNewObjectInstance(toAllocate) as IJsonReadable;
var got = newval.ReadAsJson(v, fromUI, options);//this may re-allocate the result based of newval
if (!got.match) return null;
if (typeof(IConfigSectionNode).IsreplacedignableFrom(nntp)) return (got.self as Configuration)?.Root;
return got.self;
}
//byte[] direct replacedignment w/o copies
if (nntp == typeof(byte[]))
{
if (v is byte[] preplaceded) return preplaceded;
//20210717 - #514
if (v is string str && str.IsNotNullOrWhiteSpace())
{
var buff = str.TryFromWebSafeBase64();
if (buff != null) return buff;
}
}
//field def = []
if (toType.IsArray)
{
var fvseq = v as IEnumerable;
if (fvseq == null) return null;//can not set non enumerable into array
var arr = fvseq.Cast<object>().Select(e => cast(e, toType.GetElementType(), fromUI, options, fieldCustomHandler)).ToArray();
var newval = Array.CreateInstance(toType.GetElementType(), arr.Length);
for(var i=0; i<newval.Length; i++)
newval.SetValue(arr[i], i);
return newval;
}
//field def = List<t>
if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(List<>))
{
var fvseq = v as IEnumerable;
if (fvseq == null) return false;//can not set non enumerable into List<t>
var arr = fvseq.Cast<object>().Select(e => cast(e, toType.GetGenericArguments()[0], fromUI, options, fieldCustomHandler)).ToArray();
var newval = SerializationUtils.MakeNewObjectInstance(toType) as IList;
for (var i = 0; i < arr.Length; i++)
newval.Add(arr[i]);
return newval;
}
//last resort
try
{
return StringValueConversion.AsType(v.ToString(), toType, false);
}
catch
{
return null;//the value could not be converted, and is going to go into amorphous bag if it is enabled
}
}
19
View Source File : SerializationUtils.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
public static void WalkArrayRead<T>(Array arr, Func<T> each)
{
var rank = arr.Rank;
if (rank==1)
{
var i = arr.GetLowerBound(0);
var top = arr.GetUpperBound(0);
for(; i<=top; i++)
arr.SetValue(each(), i);
return;
}
var idxs = new int[rank];
doDimensionSetValue<T>(arr, idxs, 0, each);
}
19
View Source File : SaveDuringPlay.cs
License : MIT License
Project Creator : azsumas
License : MIT License
Project Creator : azsumas
bool ScanFields(string fullName, Type type, ref object obj)
{
bool doneSomething = false;
// Check if it's a complex type
bool isLeaf = true;
if (obj != null
&& !type.IsSubclreplacedOf(typeof(Component))
&& !type.IsSubclreplacedOf(typeof(GameObject)))
{
// Is it an array?
if (type.IsArray)
{
isLeaf = false;
Array array = obj as Array;
object arrayLength = array.Length;
if (OnLeafField != null && OnLeafField(
fullName + ".Length", arrayLength.GetType(), ref arrayLength))
{
Array newArray = Array.CreateInstance(
array.GetType().GetElementType(), Convert.ToInt32(arrayLength));
Array.Copy(array, 0, newArray, 0, Math.Min(array.Length, newArray.Length));
array = newArray;
doneSomething = true;
}
for (int i = 0; i < array.Length; ++i)
{
object element = array.GetValue(i);
if (ScanFields(fullName + "[" + i + "]", array.GetType().GetElementType(), ref element))
{
array.SetValue(element, i);
doneSomething = true;
}
}
if (doneSomething)
obj = array;
}
else
{
// Check if it's a complex type
FieldInfo[] fields = obj.GetType().GetFields(bindingFlags);
if (fields.Length > 0)
{
isLeaf = false;
for (int i = 0; i < fields.Length; ++i)
{
string name = fullName + "." + fields[i].Name;
if (FilterField == null || FilterField(name, fields[i]))
{
object fieldValue = fields[i].GetValue(obj);
if (ScanFields(name, fields[i].FieldType, ref fieldValue))
{
doneSomething = true;
if (OnFieldValueChanged != null)
OnFieldValueChanged(name, fields[i], obj, fieldValue);
}
}
}
}
}
}
// If it's a leaf field then call the leaf handler
if (isLeaf && OnLeafField != null)
if (OnLeafField(fullName, type, ref obj))
doneSomething = true;
return doneSomething;
}
19
View Source File : GenericArgsBuilder.cs
License : MIT License
Project Creator : bartoszgolek
License : MIT License
Project Creator : bartoszgolek
public void SetParameterSeriesValues(MemberInfo member, ParameterSeriesAttribute parameterSeriesAttribute)
{
var method = typeof(CommandArgs).GetMethod("GetParameterSeries");
var memberType = TypeHelper.GetMemberType(member);
var generic = method.MakeGenericMethod(memberType.GetElementType());
var value = generic.Invoke(_args, null);
var itemValues = (IEnumerable) value;
var length = itemValues.Cast<object>().Count();
var array = Array.CreateInstance(memberType.GetElementType(), length);
var i = 0;
foreach (var itemValue in itemValues)
array.SetValue(itemValue, i++);
TypeHelper.SetValue(member, _tArgs, array);
}
19
View Source File : ArrayUtils.cs
License : MIT License
Project Creator : bartoszgolek
License : MIT License
Project Creator : bartoszgolek
public static object GetArray(object[] values, Type arrayType)
{
var elementType = arrayType.GetElementType();
var instance = Array.CreateInstance(elementType, values.Length);
for (var i = 0; i < values.Length; i++)
{
instance.SetValue(values[i], i);
}
return instance;
}
19
View Source File : Converter.cs
License : Apache License 2.0
Project Creator : bcgov
License : Apache License 2.0
Project Creator : bcgov
private Array AddToArray(object value, object sourceArray = null)
{
// Use the source array or create a new array.
var type = value.GetType();
var array = (Array)sourceArray ?? Array.CreateInstance(type, 0);
// Copy the existing array into a larger array.
var length = array.Length;
var newArray = Array.CreateInstance(type, length + 1);
for (var ai = 0; ai < length; ai++)
{
newArray.SetValue(array.GetValue(ai), ai);
}
// Add the new value to the array.
newArray.SetValue(value, length);
return newArray;
}
19
View Source File : BlobHelper.cs
License : MIT License
Project Creator : bitcake
License : MIT License
Project Creator : bitcake
public static Option<object> RestoreObject( BlobCollection collection, int index, System.Type type )
{
try
{
Blob blob = collection.blobs[index];
if( blob.reference != null )
return blob.reference;
if( type.IsArray )
blob.reference = System.Activator.CreateInstance( type, blob.fields.Count );
else
blob.reference = System.Activator.CreateInstance( type );
for( int i = 0; i < blob.fields.Count; i++ )
{
BlobField value = blob.fields[i];
string stringValue;
if( !value.value.TryGet( out stringValue ) )
continue;
if( type.IsArray )
{
var array = blob.reference as System.Array;
object elementValue;
if( ParseBlobValue( collection, type.GetElementType(), stringValue ).TryGet( out elementValue ) )
array.SetValue( elementValue, i );
}
else
{
FieldInfo field = type.GetField( value.name, FieldFlags );
object fieldValue;
if( ParseBlobValue( collection, field.FieldType, stringValue ).TryGet( out fieldValue ) )
field.SetValue( blob.reference, fieldValue );
}
}
return blob.reference;
}
catch( System.Exception e )
{
Debug.LogException( e );
return Functional.None;
}
}
19
View Source File : System_ArrayWrap.cs
License : MIT License
Project Creator : bjfumac
License : MIT License
Project Creator : bjfumac
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_Item(IntPtr L)
{
try
{
Array obj = ToLua.ToObject(L, 1) as Array;
if (obj == null)
{
throw new LuaException("trying to index an invalid object reference");
}
int index = (int)LuaDLL.lua_tointeger(L, 2);
Type t = obj.GetType().GetElementType();
if (t.IsValueType)
{
if (t.IsPrimitive)
{
if (SetPrimitiveValue(L, obj, t, index))
{
return 0;
}
}
else if (t == typeof(Vector3))
{
Vector3[] array = obj as Vector3[];
Vector3 val = ToLua.ToVector3(L, 3);
array[index] = val;
return 0;
}
else if (t == typeof(Quaternion))
{
Quaternion[] array = obj as Quaternion[];
Quaternion val = ToLua.ToQuaternion(L, 3);
array[index] = val;
return 0;
}
else if (t == typeof(Vector2))
{
Vector2[] array = obj as Vector2[];
Vector2 val = ToLua.ToVector2(L, 3);
array[index] = val;
return 0;
}
else if (t == typeof(Vector4))
{
Vector4[] array = obj as Vector4[];
Vector4 val = ToLua.ToVector4(L, 3);
array[index] = val;
return 0;
}
else if (t == typeof(Color))
{
Color[] array = obj as Color[];
Color val = ToLua.ToColor(L, 3);
array[index] = val;
return 0;
}
}
if (!TypeChecker.CheckType(L, t, 3))
{
return LuaDLL.luaL_typerror(L, 3, LuaMisc.GetTypeName(t));
}
object v = ToLua.CheckVarObject(L, 3, t);
v = TypeChecker.ChangeType(v, t);
obj.SetValue(v, index);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
19
View Source File : ObjectCasters.cs
License : MIT License
Project Creator : blueberryzzz
License : MIT License
Project Creator : blueberryzzz
private ObjectCast genCaster(Type type)
{
ObjectCast fixTypeGetter = (RealStatePtr L, int idx, object target) =>
{
if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA)
{
object obj = translator.SafeGetCSObj(L, idx);
return (obj != null && type.IsreplacedignableFrom(obj.GetType())) ? obj : null;
}
return null;
};
if (typeof(Delegate).IsreplacedignableFrom(type))
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_isfunction(L, idx))
{
return null;
}
return translator.CreateDelegateBridge(L, type, idx);
};
}
else if (typeof(DelegateBridgeBase).IsreplacedignableFrom(type))
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_isfunction(L, idx))
{
return null;
}
return translator.CreateDelegateBridge(L, null, idx);
};
}
else if (type.IsInterface())
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
return translator.CreateInterfaceBridge(L, type, idx);
};
}
else if (type.IsEnum())
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
LuaTypes lua_type = LuaAPI.lua_type(L, idx);
if (lua_type == LuaTypes.LUA_TSTRING)
{
return Enum.Parse(type, LuaAPI.lua_tostring(L, idx));
}
else if (lua_type == LuaTypes.LUA_TNUMBER)
{
return Enum.ToObject(type, LuaAPI.xlua_tointeger(L, idx));
}
throw new InvalidCastException("invalid value for enum " + type);
};
}
else if (type.IsArray)
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
uint len = LuaAPI.xlua_objlen(L, idx);
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
Type et = type.GetElementType();
ObjectCast elementCaster = GetCaster(et);
Array ary = target == null ? Array.CreateInstance(et, (int)len) : target as Array;
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to Array");
}
for (int i = 0; i < len; ++i)
{
LuaAPI.lua_pushnumber(L, i + 1);
LuaAPI.lua_rawget(L, idx);
if (et.IsPrimitive())
{
if (!StaticLuaCallbacks.TryPrimitiveArraySet(type, L, ary, i, n + 1))
{
ary.SetValue(elementCaster(L, n + 1, null), i);
}
}
else
{
if (InternalGlobals.genTryArraySetPtr == null
|| !InternalGlobals.genTryArraySetPtr(type, L, translator, ary, i, n + 1))
{
ary.SetValue(elementCaster(L, n + 1, null), i);
}
}
LuaAPI.lua_pop(L, 1);
}
return ary;
};
}
else if (typeof(IList).IsreplacedignableFrom(type) && type.IsGenericType())
{
Type elementType = type.GetGenericArguments()[0];
ObjectCast elementCaster = GetCaster(elementType);
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
obj = target == null ? Activator.CreateInstance(type) : target;
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
IList list = obj as IList;
uint len = LuaAPI.xlua_objlen(L, idx);
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to IList");
}
for (int i = 0; i < len; ++i)
{
LuaAPI.lua_pushnumber(L, i + 1);
LuaAPI.lua_rawget(L, idx);
if (i < list.Count && target != null)
{
if (translator.replacedignable(L, n + 1, elementType))
{
list[i] = elementCaster(L, n + 1, list[i]); ;
}
}
else
{
if (translator.replacedignable(L, n + 1, elementType))
{
list.Add(elementCaster(L, n + 1, null));
}
}
LuaAPI.lua_pop(L, 1);
}
return obj;
};
}
else if (typeof(IDictionary).IsreplacedignableFrom(type) && type.IsGenericType())
{
Type keyType = type.GetGenericArguments()[0];
ObjectCast keyCaster = GetCaster(keyType);
Type valueType = type.GetGenericArguments()[1];
ObjectCast valueCaster = GetCaster(valueType);
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
IDictionary dic = (target == null ? Activator.CreateInstance(type) : target) as IDictionary;
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
LuaAPI.lua_pushnil(L);
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to IDictionary");
}
while (LuaAPI.lua_next(L, idx) != 0)
{
if (translator.replacedignable(L, n + 1, keyType) && translator.replacedignable(L, n + 2, valueType))
{
object k = keyCaster(L, n + 1, null);
dic[k] = valueCaster(L, n + 2, !dic.Contains(k) ? null : dic[k]);
}
LuaAPI.lua_pop(L, 1); // removes value, keeps key for next iteration
}
return dic;
};
}
else if ((type.IsClreplaced() && type.GetConstructor(System.Type.EmptyTypes) != null) || (type.IsValueType() && !type.IsEnum())) //clreplaced has default construtor
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
obj = target == null ? Activator.CreateInstance(type) : target;
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to " + type);
}
/*foreach (PropertyInfo prop in type.GetProperties())
{
var _setMethod = prop.GetSetMethod();
if (_setMethod == null ||
_setMethod.IsPrivate)
{
continue;
}
LuaAPI.xlua_pushasciistring(L, prop.Name);
LuaAPI.lua_rawget(L, idx);
if (!LuaAPI.lua_isnil(L, -1))
{
try
{
prop.SetValue(obj, GetCaster(prop.PropertyType)(L, n + 1,
target == null || prop.PropertyType.IsPrimitive() || prop.PropertyType == typeof(string) ? null : prop.GetValue(obj, null)), null);
}
catch (Exception e)
{
throw new Exception("exception in tran " + prop.Name + ", msg=" + e.Message);
}
}
LuaAPI.lua_pop(L, 1);
}*/
foreach (FieldInfo field in type.GetFields())
{
LuaAPI.xlua_pushasciistring(L, field.Name);
LuaAPI.lua_rawget(L, idx);
if (!LuaAPI.lua_isnil(L, -1))
{
try
{
field.SetValue(obj, GetCaster(field.FieldType)(L, n + 1,
target == null || field.FieldType.IsPrimitive() || field.FieldType == typeof(string) ? null : field.GetValue(obj)));
}
catch (Exception e)
{
throw new Exception("exception in tran " + field.Name + ", msg=" + e.Message);
}
}
LuaAPI.lua_pop(L, 1);
}
return obj;
};
}
else
{
return fixTypeGetter;
}
}
19
View Source File : StaticLuaCallbacks.cs
License : MIT License
Project Creator : blueberryzzz
License : MIT License
Project Creator : blueberryzzz
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ArrayNewIndexer(RealStatePtr L)
#endif
{
try
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Array array = (System.Array)translator.FastGetCSObj(L, 1);
if (array == null)
{
return LuaAPI.luaL_error(L, "#1 parameter is not a array!");
}
int i = LuaAPI.xlua_tointeger(L, 2);
if (i >= array.Length)
{
return LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length);
}
Type type = array.GetType();
if (TryPrimitiveArraySet(type, L, array, i, 3))
{
return 0;
}
if (InternalGlobals.genTryArraySetPtr != null)
{
try
{
if (InternalGlobals.genTryArraySetPtr(type, L, translator, array, i, 3))
{
return 0;
}
}
catch (Exception e)
{
return LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
object val = translator.GetObject(L, 3, type.GetElementType());
array.SetValue(val, i);
return 0;
}
catch (Exception e)
{
return LuaAPI.luaL_error(L, "c# exception in ArrayNewIndexer:" + e);
}
}
See More Examples