Here are the examples of the csharp api System.ComponentModel.TypeDescriptor.GetConverter(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
684 Examples
19
Source : XmlHelper.cs
with MIT License
from 279328316
with MIT License
from 279328316
public T DeserializeNode<T>(XmlNode node = null) where T : clreplaced, new()
{
T model = new T();
XmlNode firstChild;
if (node == null)
{
node = root;
}
firstChild = node.FirstChild;
Dictionary<string, string> dict = new Dictionary<string, string>();
XmlAttributeCollection xmlAttribute = node.Attributes;
if (node.Attributes.Count > 0)
{
for (int i = 0; i < node.Attributes.Count; i++)
{
if (!dict.Keys.Contains(node.Attributes[i].Name))
{
dict.Add(node.Attributes[i].Name, node.Attributes[i].Value);
}
}
}
if (!dict.Keys.Contains(firstChild.Name))
{
dict.Add(firstChild.Name, firstChild.InnerText);
}
XmlNode next = firstChild.NextSibling;
while (next != null)
{
if (!dict.Keys.Contains(next.Name))
{
dict.Add(next.Name, next.InnerText);
}
else
{
throw new Exception($"重复的属性Key:{next.Name}");
}
next = next.NextSibling;
}
#region 为对象赋值
Type modelType = typeof(T);
List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();
foreach (PropertyInfo pi in piList)
{
string dictKey = dict.Keys.FirstOrDefault(key => key.ToLower() == pi.Name.ToLower());
if (!string.IsNullOrEmpty(dictKey))
{
string value = dict[dictKey];
TypeConverter typeConverter = TypeDescriptor.GetConverter(pi.PropertyType);
if (typeConverter != null)
{
if (typeConverter.CanConvertFrom(typeof(string)))
pi.SetValue(model, typeConverter.ConvertFromString(value));
else
{
if (typeConverter.CanConvertTo(pi.PropertyType))
pi.SetValue(model, typeConverter.ConvertTo(value, pi.PropertyType));
}
}
}
}
#endregion
return model;
}
19
Source : Helper.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static object ConvertTo(this object value, Type type)
{
var converter = TypeDescriptor.GetConverter(type);
return converter.ConvertFrom(value);
}
19
Source : Helper.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static object ConvertTo(this string value, Type type)
{
var converter = TypeDescriptor.GetConverter(type);
return converter.ConvertFromString(value);
}
19
Source : SiteSettingExpressionBuilder.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
object IExpressionBuilderProvider.Evaluate(NameValueCollection arguments, Type controlType, string propertyName, string expressionPrefix)
{
if (string.IsNullOrEmpty(arguments.GetValueByIndexOrName(0, "Name"))) ThrowArgumentException(propertyName, expressionPrefix, "Name={setting name} [, Default={default text}] [, Format={format string}] [, Portal={portal name}]");
var settingName = arguments.GetValueByIndexOrName(0, "Name");
var defaultString = arguments.GetValueByIndexOrName(1, "Default") ?? string.Empty;
var format = arguments.GetValueByIndexOrName(2, "Format");
var returnType = GetReturnType(controlType, propertyName);
var settings = new SettingDataAdapter(new PortalConfigurationDataAdapterDependencies(), HttpContext.Current.GetWebsite());
var selected = settings.Select(settingName);
var setting = selected == null ? null : selected.Enreplacedy;
if (returnType.IsA(typeof(Enreplacedy))) return setting;
if (returnType.IsA(typeof(EnreplacedyReference))) return setting == null ? null : setting.ToEnreplacedyReference();
var value = setting == null ? null : setting.GetAttributeValue<string>("adx_value");
object returnValue;
if (returnType == typeof(string) && !string.IsNullOrWhiteSpace(value) && !string.IsNullOrWhiteSpace(format))
{
returnValue = string.Format(CultureInfo.InvariantCulture, format, value);
return returnValue;
}
if (string.IsNullOrWhiteSpace(value)) value = defaultString;
if (returnType == typeof(string))
{
returnValue = value;
}
else
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
var typeConverter = TypeDescriptor.GetConverter(returnType);
returnValue = typeConverter.ConvertFromString(value);
}
return returnValue;
}
19
Source : StringExtensions.cs
with GNU General Public License v3.0
from agolaszewski
with GNU General Public License v3.0
from agolaszewski
internal static T To<T>(this string source)
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(source);
}
19
Source : StringExtensions.cs
with GNU General Public License v3.0
from agolaszewski
with GNU General Public License v3.0
from agolaszewski
internal static T? ToN<T>(this string source) where T : struct
{
if (!string.IsNullOrWhiteSpace(source))
{
try
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(source);
}
catch
{
return null;
}
}
return null;
}
19
Source : RoleStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public virtual TKey ConvertIdFromString(string id)
{
if (id == null)
{
return default;
}
return (TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString(id);
}
19
Source : JsonTypeReflector.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static TypeConverter GetTypeConverter(Type type)
{
return TypeDescriptor.GetConverter(type);
}
19
Source : TypeExtensions.cs
with MIT License
from albyho
with MIT License
from albyho
public static bool IsComplexType(this Type type)
{
return !TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string));
}
19
Source : StringExtensions.cs
with MIT License
from alexandre-spieser
with MIT License
from alexandre-spieser
public static TKey ToTKey<TKey>(this string id)
{
if (id == null)
{
return default(TKey);
}
var typeOfKey = typeof(TKey);
if (typeOfKey.Name != "ObjectId")
{
return (TKey)TypeDescriptor.GetConverter(typeOfKey).ConvertFromInvariantString(id);
}
return (TKey)(object)(new ObjectId(id));
}
19
Source : SyntaxTreeToQueryConvertor.cs
with MIT License
from alirezanet
with MIT License
from alirezanet
private static LambdaExpression? GenerateExpression(
Expression body,
ParameterExpression parameter,
ValueExpressionSyntax valueExpression,
SyntaxNode op,
bool allowNullSearch,
Func<string, object>? convertor)
{
// Remove the boxing for value types
if (body.NodeType == ExpressionType.Convert) body = ((UnaryExpression)body).Operand;
object? value = valueExpression.ValueToken.Text;
// execute user custom Convertor
if (convertor != null)
value = convertor.Invoke(valueExpression.ValueToken.Text) ?? null;
// handle the `null` keyword in value
if (allowNullSearch && op.Kind is SyntaxKind.Equal or SyntaxKind.NotEqual && value?.ToString() == "null")
value = null;
// type fixer
if (value is not null && body.Type != value.GetType())
{
try
{
// handle broken guids, github issue #2
if (body.Type == typeof(Guid) && !Guid.TryParse(value!.ToString(), out _)) value = Guid.NewGuid().ToString();
var converter = TypeDescriptor.GetConverter(body.Type);
value = converter.ConvertFromString(value!.ToString())!;
}
catch (FormatException)
{
// return no records in case of any exception in formatting
return Expression.Lambda(Expression.Constant(false), parameter); // q => false
}
}
// handle case-Insensitive search
if (value is not null && valueExpression.IsCaseInsensitive
&& op.Kind is not SyntaxKind.GreaterThan
&& op.Kind is not SyntaxKind.LessThan
&& op.Kind is not SyntaxKind.GreaterOrEqualThan
&& op.Kind is not SyntaxKind.LessOrEqualThan)
{
value = value.ToString().ToLower();
body = Expression.Call(body, GetToLowerMethod());
}
Expression be;
// use string.Compare instead of operators if value and field are both strings
var areBothStrings = body.Type == typeof(string) && value?.GetType() == typeof(string);
switch (op.Kind)
{
case SyntaxKind.Equal when !valueExpression.IsNullOrDefault:
be = Expression.Equal(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.Equal when valueExpression.IsNullOrDefault:
if (body.Type == typeof(string))
be = Expression.Call(null, GetIsNullOrEmptyMethod(), body);
else
{
var canBeNull = !body.Type.IsValueType || (Nullable.GetUnderlyingType(body.Type) != null);
be = canBeNull
? Expression.OrElse(Expression.Equal(body, Expression.Constant(null)), Expression.Equal(body, Expression.Default(body.Type)))
: Expression.Equal(body, Expression.Default(body.Type));
}
break;
case SyntaxKind.NotEqual when !valueExpression.IsNullOrDefault:
be = Expression.NotEqual(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.NotEqual when valueExpression.IsNullOrDefault:
if (body.Type == typeof(string))
be = Expression.Not(Expression.Call(null, GetIsNullOrEmptyMethod(), body));
else
{
var canBeNull = !body.Type.IsValueType || (Nullable.GetUnderlyingType(body.Type) != null);
be = canBeNull
? Expression.AndAlso(Expression.NotEqual(body, Expression.Constant(null)),
Expression.NotEqual(body, Expression.Default(body.Type)))
: Expression.NotEqual(body, Expression.Default(body.Type));
}
break;
case SyntaxKind.GreaterThan when areBothStrings == false:
be = Expression.GreaterThan(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.LessThan when areBothStrings == false:
be = Expression.LessThan(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.GreaterOrEqualThan when areBothStrings == false:
be = Expression.GreaterThanOrEqual(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.LessOrEqualThan when areBothStrings == false:
be = Expression.LessThanOrEqual(body, GetValueExpression(body.Type, value));
break;
case SyntaxKind.GreaterThan when areBothStrings:
be = GetGreaterThanExpression(body, valueExpression, value);
break;
case SyntaxKind.LessThan when areBothStrings:
be = GetLessThanExpression(body, valueExpression, value);
break;
case SyntaxKind.GreaterOrEqualThan when areBothStrings:
be = GetGreaterThanOrEqualExpression(body, valueExpression, value);
break;
case SyntaxKind.LessOrEqualThan when areBothStrings:
be = GetLessThanOrEqualExpression(body, valueExpression, value);
break;
case SyntaxKind.Like:
be = Expression.Call(body, GetContainsMethod(), GetValueExpression(body.Type, value));
break;
case SyntaxKind.NotLike:
be = Expression.Not(Expression.Call(body, GetContainsMethod(), GetValueExpression(body.Type, value)));
break;
case SyntaxKind.StartsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value?.ToString()));
}
else
be = Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value));
break;
case SyntaxKind.EndsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value?.ToString()));
}
else
be = Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value));
break;
case SyntaxKind.NotStartsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Not(Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value?.ToString())));
}
else
be = Expression.Not(Expression.Call(body, GetStartWithMethod(), GetValueExpression(body.Type, value)));
break;
case SyntaxKind.NotEndsWith:
if (body.Type != typeof(string))
{
body = Expression.Call(body, GetToStringMethod());
be = Expression.Not(Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value?.ToString())));
}
else
be = Expression.Not(Expression.Call(body, GetEndsWithMethod(), GetValueExpression(body.Type, value)));
break;
default:
return null;
}
return Expression.Lambda(be, parameter);
}
19
Source : ObjectExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static T To<T>(this object @this)
{
if (@this == null)
{
return (T)(object)null;
}
var targetType = typeof(T);
if (@this.GetType() == targetType)
{
return (T)@this;
}
var converter = TypeDescriptor.GetConverter(@this);
if (converter != null && converter.CanConvertTo(targetType))
return (T)converter.ConvertTo(@this, targetType);
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null&& converter.CanConvertFrom(@this.GetType()))
return (T)converter.ConvertFrom(@this);
if (@this == DBNull.Value)
{
return (T)(object)null;
}
return (T)Convert.ChangeType(@this, targetType);
}
19
Source : ObjectExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static object To([MaybeNull] this object @this, Type type)
{
if (@this != null)
{
var targetType = type;
if (@this.GetType() == targetType)
{
return @this;
}
var converter = TypeDescriptor.GetConverter(@this);
if (converter != null&& converter.CanConvertTo(targetType))
return converter.ConvertTo(@this, targetType);
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null&& converter.CanConvertFrom(@this.GetType()))
return converter.ConvertFrom(@this);
if (@this == DBNull.Value)
return null;
return Convert.ChangeType(@this, targetType);
}
return @this;
}
19
Source : YoloConfigParser.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
private static T ParseValue<T>(string value)
{
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
return (T)converter.ConvertFromString(null, CultureInfo.InvariantCulture, value);
}
return default(T);
}
catch (NotSupportedException)
{
return default(T);
}
}
19
Source : HelpPageConfigurationExtensions.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
19
Source : JsonMapper.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
private static object ReadValue(Type inst_type, JsonReader reader)
{
reader.Read();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null)
{
#if NETSTANDARD1_5
if (inst_type.IsClreplaced() || underlying_type != null) {
return null;
}
#else
if (inst_type.IsClreplaced || underlying_type != null)
{
return null;
}
#endif
throw new JsonException(String.Format("Can't replacedign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean)
{
Type json_type = reader.Value.GetType();
if (value_type.IsreplacedignableFrom(json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey(json_type) &&
custom_importers_table[json_type].ContainsKey(value_type))
{
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer(reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey(json_type) &&
base_importers_table[json_type].ContainsKey(value_type))
{
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer(reader.Value);
}
// Maybe it's an enum
#if NETSTANDARD1_5
if (value_type.IsEnum())
return Enum.ToObject (value_type, reader.Value);
#else
if (value_type.IsEnum)
return Enum.ToObject(value_type, reader.Value);
#endif
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp(value_type, json_type);
if (conv_op != null)
return conv_op.Invoke(null,
new object[] { reader.Value });
// No luck
throw new JsonException(String.Format("Can't replacedign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart)
{
AddArrayMetadata(inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (!t_data.IsArray && !t_data.IsList)
throw new JsonException(String.Format("Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (!t_data.IsArray)
{
list = (IList) Activator.CreateInstance(inst_type);
elem_type = t_data.ElementType;
}
else
{
list = new ArrayList();
elem_type = inst_type.GetElementType();
}
while (true)
{
object item = ReadValue(elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add(item);
}
if (t_data.IsArray)
{
int n = list.Count;
instance = Array.CreateInstance(elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue(list[i], i);
}
else
instance = list;
}
else if (reader.Token == JsonToken.ObjectStart)
{
AddObjectMetadata(value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance(value_type);
while (true)
{
reader.Read();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey(property))
{
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField)
{
((FieldInfo) prop_data.Info).SetValue(instance, ReadValue(prop_data.Type, reader));
}
else
{
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue(instance,
ReadValue(prop_data.Type, reader),
null);
else
ReadValue(prop_data.Type, reader);
}
}
else
{
if (!t_data.IsDictionary)
{
if (!reader.SkipNonMembers)
{
throw new JsonException(String.Format("The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
}
ReadSkip(reader);
continue;
}
var dicTypes = instance.GetType().GetGenericArguments();
var converter = System.ComponentModel.TypeDescriptor.GetConverter(dicTypes[0]);
object key = property;
if (converter != null)
{
key = converter.ConvertFromString(property);
t_data.ElementType = dicTypes[1];
}
((IDictionary) instance).Add(key, ReadValue(t_data.ElementType, reader));
}
}
}
return instance;
}
19
Source : Options.cs
with MIT License
from aolszowka
with MIT License
from aolszowka
protected static T Parse<T> (string value, OptionContext c)
{
TypeConverter conv = TypeDescriptor.GetConverter (typeof (T));
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, typeof (T).Name, c.OptionName),
c.OptionName, e);
}
return t;
}
19
Source : ConvertUtilTest.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
internal T GetTypedValue<T>(object v)
{
if (v == null)
{
return default(T);
}
Type fromType = v.GetType();
Type toType = typeof(T);
Type toType2 = (TypeCompat.IsGenericType(toType) && toType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
? Nullable.GetUnderlyingType(toType)
: null;
if (fromType == toType || fromType == toType2)
{
return (T)v;
}
var cnv = TypeDescriptor.GetConverter(fromType);
if (toType == typeof(DateTime) || toType2 == typeof(DateTime)) //Handle dates
{
if (fromType == typeof(TimeSpan))
{
return ((T)(object)(new DateTime(((TimeSpan)v).Ticks)));
}
else if (fromType == typeof(string))
{
DateTime dt;
if (DateTime.TryParse(v.ToString(), out dt))
{
return (T)(object)(dt);
}
else
{
return default(T);
}
}
else
{
if (cnv.CanConvertTo(typeof(double)))
{
return (T)(object)(DateTime.FromOADate((double)cnv.ConvertTo(v, typeof(double))));
}
else
{
return default(T);
}
}
}
else if (toType == typeof(TimeSpan) || toType2 == typeof(TimeSpan)) //Handle timespan
{
if (fromType == typeof(DateTime))
{
return ((T)(object)(new TimeSpan(((DateTime)v).Ticks)));
}
else if (fromType == typeof(string))
{
TimeSpan ts;
if (TimeSpan.TryParse(v.ToString(), out ts))
{
return (T)(object)(ts);
}
else
{
return default(T);
}
}
else
{
if (cnv.CanConvertTo(typeof(double)))
{
return (T)(object)(new TimeSpan(DateTime.FromOADate((double)cnv.ConvertTo(v, typeof(double))).Ticks));
}
else
{
try
{
// Issue 14682 -- "GetValue<decimal>() won't convert strings"
// As suggested, after all special cases, all .NET to do it's
// preferred conversion rather than simply returning the default
return (T)Convert.ChangeType(v, typeof(T));
}
catch (Exception)
{
// This was the previous behaviour -- no conversion is available.
return default(T);
}
}
}
}
else
{
if (cnv.CanConvertTo(toType))
{
return (T)cnv.ConvertTo(v, typeof(T));
}
else
{
if (toType2 != null)
{
toType = toType2;
if (cnv.CanConvertTo(toType))
{
return (T)cnv.ConvertTo(v, toType); //Fixes issue 15377
}
}
if (fromType == typeof(double) && toType == typeof(decimal))
{
return (T)(object)Convert.ToDecimal(v);
}
else if (fromType == typeof(decimal) && toType == typeof(double))
{
return (T)(object)Convert.ToDouble(v);
}
else
{
return default(T);
}
}
}
}
19
Source : MockTableImportFixed.cs
with MIT License
from Apps72
with MIT License
from Apps72
private IEnumerable<object[]> GetRowsConverted(IEnumerable<string[]> rows)
{
int fieldsCount = Fields.Count();
Type[] fieldsType = Fields.Select(i => i.DataType).ToArray();
foreach (var row in rows)
{
var rowConverted = new object[fieldsCount];
for (int i = 0; i < fieldsCount; i++)
{
try
{
// If not a string => String.Empty = NULL
if (fieldsType[i] != typeof(string) && String.IsNullOrEmpty(row[i]))
{
row[i] = "NULL";
}
if (fieldsType[i] != null && String.Compare(row[i], "NULL", ignoreCase: true) != 0)
{
// Convert
var converter = System.ComponentModel.TypeDescriptor.GetConverter(fieldsType[i]);
rowConverted[i] = Convert.ChangeType(converter.ConvertFromInvariantString(row[i]), fieldsType[i]);
// Guillemets
if (fieldsType[i] == typeof(string) && row[i].Length >= 2 && row[i][0] == '"' && row[i][row[i].Length - 1] == '"')
{
rowConverted[i] = row[i].Substring(1, row[i].Length - 2);
}
}
}
catch (Exception)
{
throw new InvalidCastException($"Invalid conversion of \"{row[i]}\" to \"{fieldsType[i].Name}\", for column \"{Fields.ElementAt(i).Name}\".");
}
}
yield return rowConverted;
}
}
19
Source : InstantHandler.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override Instant Parse(object value)
{
if (value == null || value is DBNull) return default;
if (value is DateTime dateTime)
{
var dt = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
return Instant.FromDateTimeUtc(dt);
}
if (value is DateTimeOffset dateTimeOffset)
{
return Instant.FromDateTimeOffset(dateTimeOffset);
}
if (value is string s)
{
var conv = TypeDescriptor.GetConverter(typeof(Instant));
if (conv?.CanConvertFrom(typeof(string)) == true)
return (Instant)conv.ConvertFromString(s);
}
throw new DataException("Cannot convert " + value.GetType() + " to NodaTime.Instant");
}
19
Source : LocalDateHandler.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override LocalDate Parse(object value)
{
if (value == null || value is DBNull) return default;
if (value is DateTime dateTime)
{
return LocalDateTime.FromDateTime(dateTime).Date;
}
if (value is string s)
{
var conv = TypeDescriptor.GetConverter(typeof(LocalDate));
if (conv?.CanConvertFrom(typeof(string)) == true)
return (LocalDate)conv.ConvertFromString(s);
}
throw new DataException("Cannot convert " + value.GetType() + " to NodaTime.LocalDate");
}
19
Source : LocalDateTimeHandler.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override LocalDateTime Parse(object value)
{
if (value == null || value is DBNull) return default;
if (value is DateTime dateTime)
{
return LocalDateTime.FromDateTime(dateTime);
}
if (value is string s)
{
var conv = TypeDescriptor.GetConverter(typeof(LocalDateTime));
if (conv?.CanConvertFrom(typeof(string)) == true)
return (LocalDateTime)conv.ConvertFromString(s);
}
throw new DataException("Cannot convert " + value.GetType() + " to NodaTime.LocalDateTime");
}
19
Source : LocalTimeHandler.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override LocalTime Parse(object value)
{
if (value == null || value is DBNull) return default;
if (value is TimeSpan timeSpan)
{
return LocalTime.FromTicksSinceMidnight(timeSpan.Ticks);
}
if (value is DateTime dateTime)
{
return LocalTime.FromTicksSinceMidnight(dateTime.TimeOfDay.Ticks);
}
if (value is string s)
{
var conv = TypeDescriptor.GetConverter(typeof(LocalTime));
if (conv?.CanConvertFrom(typeof(string)) == true)
return (LocalTime)conv.ConvertFromString(s);
}
throw new DataException("Cannot convert " + value.GetType() + " to NodaTime.LocalTime");
}
19
Source : OffsetDateTimeHandler.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override OffsetDateTime Parse(object value)
{
if (value == null || value is DBNull) return default;
if (value is DateTimeOffset dateTimeOffset)
{
return OffsetDateTime.FromDateTimeOffset(dateTimeOffset);
}
if (value is string s)
{
var conv = TypeDescriptor.GetConverter(typeof(OffsetDateTime));
if (conv?.CanConvertFrom(typeof(string)) == true)
return (OffsetDateTime)conv.ConvertFromString(s);
}
throw new DataException("Cannot convert " + value.GetType() + " to NodaTime.OffsetDateTime");
}
19
Source : GenericDictionaryWithConvertibleKey.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override bool CanConvert(Type typeToConvert)
{
Type actualTypeToConvert;
Type keyType = null;
if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClreplaced(typeof(Dictionary<,>))) != null)
{
keyType = actualTypeToConvert.GetGenericArguments()[0];
}
else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IDictionary<,>))) != null)
{
keyType = actualTypeToConvert.GetGenericArguments()[0];
}
else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IReadOnlyDictionary<,>))) != null)
{
keyType = actualTypeToConvert.GetGenericArguments()[0];
}
if (keyType != null && keyType != typeof(string))
{
var converter = TypeDescriptor.GetConverter(keyType);
return converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(typeof(string));
}
return false;
}
19
Source : UniversalInvariantTypeConverterJsonConverter.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var typeConverter = TypeDescriptor.GetConverter(typeToConvert);
var jsonConverter = (JsonConverter?)Activator.CreateInstance(typeof(TypeConverterJsonConverter<>).MakeGenericType(
new Type[] { typeToConvert }),
new object[] { typeConverter, options });
return jsonConverter;
}
19
Source : Options.cs
with MIT License
from atifaziz
with MIT License
from atifaziz
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
19
Source : UAGUtils.cs
with MIT License
from atenfyr
with MIT License
from atenfyr
public static object ArbitraryTryParse(this string input, Type type)
{
try
{
var converter = TypeDescriptor.GetConverter(type);
if (converter != null)
{
return converter.ConvertFromString(input);
}
}
catch (NotSupportedException) { }
return null;
}
19
Source : NDesk.Options.cs
with Apache License 2.0
from atifaziz
with Apache License 2.0
from atifaziz
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
19
Source : DefaultSettings.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
static public void ResetToDefault (ApplicationSettingsBase settings) {
foreach (var o in settings.Properties) {
if (o is SettingsProperty prop) {
var val = TypeDescriptor.GetConverter (prop.PropertyType).ConvertFromString (prop.DefaultValue as string);
settings[prop.Name] = val;
}
}
}
19
Source : NewtonsoftJsonCloudEventSerializer.cs
with MIT License
from Avanade
with MIT License
from Avanade
public Task<EventData?> DeserializeAsync(Type valueType, byte[] bytes)
{
var d = Deserialize(bytes);
if (d.CloudEvent?.Data == null)
return Task.FromResult<EventData?>(null);
if (d.CloudEvent.DataContentType != MediaTypeNames.Application.Json)
throw new InvalidOperationException($"CloudEvent DataContentType.MediaType is '{d.CloudEvent.DataContentType}'; it must be '{MediaTypeNames.Application.Json}' to use the '{nameof(NewtonsoftJsonCloudEventSerializer)}'.");
var ed = (EventData)Activator.CreateInstance(NewtonsoftJsonEventDataSerializer.CreateValueEventDataType(valueType), new object[] { d.Metadata! });
ed.SetValue(d.CloudEvent.Data is JToken json ? json.ToObject(valueType)
: (d.CloudEvent.Data is string str ? TypeDescriptor.GetConverter(valueType).ConvertFromInvariantString(str) : Convert.ChangeType(d.CloudEvent.Data, valueType)));
return Task.FromResult<EventData?>(ed);
}
19
Source : ValueRangeTextBox.cs
with MIT License
from ay2015
with MIT License
from ay2015
protected virtual string QueryTextFromValueCore(object value)
{
if (value == null || value == DBNull.Value)
{
return string.Empty;
}
IFormatProvider activeFormatProvider = GetActiveFormatProvider();
CultureInfo cultureInfo = activeFormatProvider as CultureInfo;
if (cultureInfo != null)
{
TypeConverter converter = TypeDescriptor.GetConverter(value.GetType());
if (converter.CanConvertTo(typeof(string)))
{
return (string)converter.ConvertTo(null, cultureInfo, value, typeof(string));
}
}
try
{
return Convert.ToString(value, activeFormatProvider);
}
catch
{
}
return value.ToString();
}
19
Source : TypeConverterHelper.cs
with MIT License
from ay2015
with MIT License
from ay2015
internal static TypeConverter GetTypeConverter(Type type)
{
return TypeDescriptor.GetConverter(type);
}
19
Source : EnumerableExtensions.cs
with Apache License 2.0
from azanov
with Apache License 2.0
from azanov
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this NameValueCollection col)
{
var dict = new Dictionary<TKey, TValue>();
TypeConverter keyConverter = TypeDescriptor.GetConverter(typeof(TKey));
TypeConverter valueConverter = TypeDescriptor.GetConverter(typeof(TValue));
foreach (string name in col)
{
var key = (TKey)keyConverter.ConvertFromString(name);
var value = (TValue)valueConverter.ConvertFromString(col[name]);
dict.Add(key, value);
}
return dict;
}
19
Source : QRTestForm.cs
with MIT License
from azist
with MIT License
from azist
private void Generate(string content, QRCorrectionLevel correctionLevel, QRImageRenderer.ImageScale scale)
{
Matrix = null;
Matrix = QREncoderMatrix.Encode(content, correctionLevel);
using (MemoryStream stream = new MemoryStream())
{
Matrix.ToBMP(stream, scale: scale);
stream.Flush();
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bmp = converter.ConvertFrom(stream.ToArray()) as Bitmap;
m_pnlImage.BackgroundImage = bmp;
m_txtTrace.Text = Matrix.ToString();
}
}
19
Source : HelpPageConfigurationExtensions.cs
with MIT License
from Azure
with MIT License
from Azure
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
19
Source : ObjectEx.cs
with MIT License
from Azure
with MIT License
from Azure
public static object As(this object value, Type type) {
if (value == null || value.GetType() == type) {
return value;
}
var converter = TypeDescriptor.GetConverter(type);
return converter.ConvertFrom(value);
}
19
Source : LegacyCliOptions.cs
with MIT License
from Azure
with MIT License
from Azure
private T GetValueOrDefault<T>(string key, T defaultValue) {
if (!ContainsKey(key)) {
return defaultValue;
}
var converter = TypeDescriptor.GetConverter(typeof(T));
return (T)converter.ConvertFrom(this[key]);
}
19
Source : Comment.cs
with MIT License
from Azure-Functions
with MIT License
from Azure-Functions
private static object ConvertParameter(string parameter, Type targetType)
{
return String.IsNullOrWhiteSpace(parameter)
? null
: TypeDescriptor.GetConverter(targetType).ConvertFrom(parameter);
}
19
Source : Commands.cs
with MIT License
from barncastle
with MIT License
from barncastle
private static bool Read<T>(string[] args, uint index, out T result) where T : unmanaged
{
if (index < args.Length)
{
var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
if (converter.IsValid(args[index]))
{
result = (T)converter.ConvertFromString(args[index]);
return true;
}
}
result = default;
return false;
}
19
Source : Options.cs
with The Unlicense
from BattletechModders
with The Unlicense
from BattletechModders
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
#if PCL
TypeInfo ti = tt.GetTypeInfo ();
#else
Type ti = tt;
#endif
bool nullable =
ti.IsValueType &&
ti.IsGenericType &&
!ti.IsGenericTypeDefinition &&
ti.GetGenericTypeDefinition () == typeof (Nullable<>);
#if PCL
Type targetType = nullable ? tt.GenericTypeArguments [0] : tt;
#else
Type targetType = nullable ? tt.GetGenericArguments () [0] : tt;
#endif
T t = default (T);
try {
if (value != null) {
#if PCL
if (targetType.GetTypeInfo ().IsEnum)
t = (T) Enum.Parse (targetType, value, true);
else
t = (T) Convert.ChangeType (value, targetType);
#else
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
t = (T) conv.ConvertFromString (value);
#endif
}
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
19
Source : IExpressionExtensions.cs
with MIT License
from bbartels
with MIT License
from bbartels
public static void ValidatePropertyType(this IExpression exp, string key, IEnumerable<string> values)
{
if (exp.PropertyType == typeof(string)) { return; }
var currentValue = string.Empty;
try
{
var converter = TypeDescriptor.GetConverter(exp.PropertyType);
foreach (var value in values)
{
currentValue = value;
converter?.ConvertFromString(value);
}
}
catch (NotSupportedException)
{
throw new InvalidQueryException($"Value: '{currentValue}' does not match " +
$"datatype: '{exp.PropertyType}' of registered key: '{key}'");
}
}
19
Source : BaseGenericObjectParser.cs
with MIT License
from bcssov
with MIT License
from bcssov
protected static TypeConverter GetConverter<T>()
{
TypeConverter converter;
if (converters.ContainsKey(typeof(T)))
{
converter = converters[typeof(T)];
}
else
{
converter = TypeDescriptor.GetConverter(typeof(T));
converters.TryAdd(typeof(T), converter);
}
return converter;
}
19
Source : ComponentModelTypeDescriptor.cs
with MIT License
from bilal-fazlani
with MIT License
from bilal-fazlani
public bool CanSupport(Type type)
{
var typeConverter = TypeDescriptor.GetConverter(type);
return typeConverter.CanConvertFrom(typeof(string));
}
19
Source : ComponentModelTypeDescriptor.cs
with MIT License
from bilal-fazlani
with MIT License
from bilal-fazlani
public object? ParseString(IArgument argument, string value)
{
var typeConverter = argument.Arity.AllowsMany()
? TypeDescriptor.GetConverter(argument.TypeInfo.UnderlyingType)
: TypeDescriptor.GetConverter(argument.TypeInfo.Type);
return typeConverter.ConvertFrom(value)!;
}
19
Source : IDbConnection.Extensions.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
public static T ExecuteScalar<T>(this IDbConnection connection, string sql, params object[] sqlParams)
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
using var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
foreach (var param in sqlParams)
{
command.Parameters.Add(param);
}
var objValue = command.ExecuteScalar();
T result = default;
if (objValue != null)
{
var returnType = typeof(T);
var converter = TypeDescriptor.GetConverter(returnType);
if (converter.CanConvertFrom(objValue.GetType()))
{
result = (T)converter.ConvertFrom(objValue);
}
else
{
result = (T)Convert.ChangeType(objValue, returnType);
}
}
return result;
}
19
Source : JSObject.cs
with MIT License
from BlazorExtensions
with MIT License
from BlazorExtensions
object UnWrapObject(Type type, object obj)
{
if (type.IsPrimitive || typeof(Decimal) == type)
{
return Convert.ChangeType(obj, type);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var conv = System.ComponentModel.TypeDescriptor.GetConverter(type);
if (!conv.CanConvertFrom(obj.GetType()))
{
throw new NotSupportedException();
}
if (conv.IsValid(obj))
{
return conv.ConvertFrom(obj);
}
throw new InvalidCastException();
}
else if (type.IsEnum)
{
return RuntimeUtilities.EnumFromExportContract(type, obj);
}
else if (type == typeof(string))
{
return obj;
}
else if (type.IsSubclreplacedOf(typeof(JSObject)) || type == typeof(JSObject))
{
if (obj == null)
return (object)null;
var jsobject = obj.ToString();
var jsobjectnew = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] { typeof(Int32) }, null);
return jsobjectnew.Invoke(new object[] { (jsobject == null) ? -1 : Int32.Parse(jsobject) });
}
else if (type is object)
{
// called via invoke
if (obj == null)
return (object)null;
else
throw new NotSupportedException($"Type {type} not supported yet.");
}
else
{
throw new NotSupportedException($"Type {type} not supported yet.");
}
}
19
Source : Option.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
with BSD 3-Clause "New" or "Revised" License
from Bluegrams
public void SetFromString(string s)
{
string[] split = s.Split(' ');
string stringValue = s.Substring(split[0].Length).Trim().Trim('"');
if (!OptionStrings.Contains(split[0]))
throw new ArgumentException("Given string does not match required format.");
if (Value is bool)
{
Value = (T)(object)OptionStrings.Contains(s);
}
else if (Value is Enum)
{
string replacedleCase = CultureInfo.InvariantCulture.TextInfo.ToreplacedleCase(stringValue);
Value = (T)Enum.Parse(typeof(T), replacedleCase);
}
else if (Value is DateTime)
{
Value = (T)(object)DateTime.ParseExact(stringValue, "yyyyMMdd", null);
}
else
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
Value = (T)conv.ConvertFrom(stringValue);
}
}
19
Source : PlayerPrefsMemory.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public T Get<T>(string key)
{
var type = typeof(T);
var converter = TypeDescriptor.GetConverter(type);
if (_dataGetter.ContainsKey(type))
{
return (T) converter.ConvertTo(_dataGetter[type](key), type);
}
Debug.LogError("当前数据存储中无此类型数据,类型名:" + typeof(T).Name);
return default(T);
}
19
Source : JsonReader.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
private T GetValue<T>(JsonData data)
{
var converter = TypeDescriptor.GetConverter(typeof(T));
try
{
if (converter.CanConvertTo(typeof(T)))
return (T) converter.ConvertTo(data.ToString(), typeof(T));
return (T) (object) data;
}
catch (Exception e)
{
Debug.LogError("当前类型转换出现问题,目标类型为:" + typeof(T).Name + " data:" + data);
return default(T);
}
}
See More Examples