qmlnet/src/net/Qml.Net/Extensions/INetJsValueExtensions.cs
2018-12-30 20:35:57 -05:00

44 lines
No EOL
1.2 KiB
C#

using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
namespace Qml.Net.Extensions
{
public static class NetJsValueExtensions
{
public static List<T> AsList<T>(this INetJsValue value)
{
if (value == null || !value.IsArray)
{
return null;
}
if (typeof(T) != typeof(int) && typeof(T) != typeof(string))
{
// Only enumerables of int and string are currently supported
return null;
}
var destinationConverter = TypeDescriptor.GetConverter(typeof(T));
var list = new List<T>();
var length = (int)value.GetProperty("length");
for (var i = 0; i < length; i++)
{
var item = value.GetItemAtIndex(i);
if (item is T casted)
{
list.Add(casted);
}
else
{
list.Add((T)destinationConverter.ConvertFrom(null, CultureInfo.InvariantCulture, item));
}
}
return list;
}
}
}