System.Convert.ChangeType(object, System.Type)

Here are the examples of the csharp api System.Convert.ChangeType(object, System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1407 Examples 7

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static object ChangeType(object obj, Type type)
		{
			if (obj == null || obj == DBNull.Value)
				return null;
			if (obj.GetType() == type)
				return obj;
			if (type == typeof(object))
				return obj;

			object result = null;
			try
			{
				if (obj is string)
				{
					if (_deserializeMethods.ContainsKey(type))
					{
						var method = _deserializeMethods[type];
						result = method.Invoke(_single, new object[] { obj as string });
					}
					else
					{
						if (type.IsEnum)
							result = Enum.Parse(type, obj as string);
						else
							result = System.Convert.ChangeType(obj, type);
					}
				}
				else if (type == typeof(string))
				{
					if (_serializeMethods.ContainsKey(obj.GetType()))
					{
						var method = _serializeMethods[obj.GetType()];
						result = method.Invoke(_single, new object[] { obj }) as string;
					}
					else
						result = obj.ToString();
				}
				else
				{
					if (type.IsEnum)
						result = Enum.ToObject(type, obj);
					else
						result = System.Convert.ChangeType(obj, type);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return result;
		}

19 View Source File : AppDomainHelper.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public static T InvokeOnAppDomain<T>(AppDomain appDomain, CrossAppDomainCallRetValueDelegate targetFunc, params object[] payload)
        {
            appDomain.SetData(appDomain.FriendlyName + "_payload", payload);
            appDomain.SetData(appDomain.FriendlyName + "_func", targetFunc);
            appDomain.DoCallBack(InvokedOnAppDomainRet);

            return (T)Convert.ChangeType(appDomain.GetData("result"), typeof(T));
        }

19 View Source File : StringsOnXAxis.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatLabel(IComparable dataValue)
        {
            int labelValue = (int)Convert.ChangeType(dataValue, typeof(int));
            return _labelsMap.ContainsKey(labelValue) ? _labelsMap[labelValue] : labelValue + " Not in map!";
        }

19 View Source File : Map.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static T FromDictionary<T>(Dictionary<string, object> dictionary) where T : new()
        {
            if (dictionary == null)
            {
                return default;
            }

            var user = new T();
            var type = user.GetType();
            foreach (var key in dictionary.Keys)
            {
                var property = type.GetProperty(key);
                var value = dictionary[key];
                var valueType = value?.GetType();
                if (value != null && valueType != property.PropertyType)
                {
                    if (valueType == typeof(Timestamp))
                    {
                        value = ConvertFromDate(property, value);
                    }
                    else
                    {
                        value = Convert.ChangeType(value, property.PropertyType);
                    }
                }
                property.SetValue(user, value);
            }
            return user;
        }

19 View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : Accelerider

public static T CastTo<T>(this object value)
        {
            return typeof(T).IsValueType && value != null
                ? (T)Convert.ChangeType(value, typeof(T))
                : value is T typeValue ? typeValue : default;
        }

19 View Source File : BitfinexResultConverter.cs
License : MIT License
Project Creator : aabiryukov

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType == null) throw new ArgumentNullException(nameof(objectType));

            var result = Activator.CreateInstance(objectType);
            var arr = JArray.Load(reader);
            foreach (var property in objectType.GetProperties())
            {
                var attribute =
                    (BitfinexPropertyAttribute) property.GetCustomAttribute(typeof(BitfinexPropertyAttribute));
                if (attribute == null)
                    continue;

                if (attribute.Index >= arr.Count)
                    continue;

                object value;
                var converterAttribute = (JsonConverterAttribute) property.GetCustomAttribute(typeof(JsonConverterAttribute));
                if (converterAttribute != null)
                    value = arr[attribute.Index].ToObject(property.PropertyType, new JsonSerializer() { Converters = { (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType) } });
                else
                    value = arr[attribute.Index];                

                if (property.PropertyType.IsreplacedignableFrom(value.GetType()))
                    property.SetValue(result, value);
                else
                    property.SetValue(result, value == null ? null : Convert.ChangeType(value, property.PropertyType));
            }
            return result;
        }

19 View Source File : INIFile.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal T GetValue<T>(string section, string key, T defaultValue = default)
        {
            if (!ValueExists(section, key))
            {
                if ((defaultValue == null) && (typeof(T) == typeof(string))) return (T)Convert.ChangeType("", typeof(T));
                return defaultValue;
            }

            string val = ReadValue(section, key) ?? "";

            try
            {
                if (CanConvertStringTo<T>())
                    return ConvertStringTo(val, defaultValue);
                else
                    return default;
            }
            catch (Exception)
            {
                return default;
            }
        }

19 View Source File : JsonMapper.cs
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 : LightDataTableRow.cs
License : MIT License
Project Creator : AlenToma

public object ValueAndConvert(Type type, string key, bool loadDefault = false)
        {
            var v = this[key, loadDefault];
            if (v != DBNull.Value && v != null && v.GetType() != Columns[key].DataType && !(type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(Nullable<>)) && v != "")
                return Convert.ChangeType(this[key], type);
            if (v == null || v == DBNull.Value || string.IsNullOrEmpty(v.ToString()))
            {
                TypeValidation(ref v, type, true);
                if (v == null && type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(Nullable<>))
                    return ValueByType(type);
            }
            else
                TypeValidation(ref v, type, false);

            if (v?.GetType() != type && (!type.GetTypeInfo().IsGenericType || type.GetTypeInfo().GetGenericTypeDefinition() != typeof(Nullable<>)))
                return Convert.ChangeType(v, type);

            return v?.GetType() != type ? Convert.ChangeType(v, type.GetGenericArguments()[0]) : v;
        }

19 View Source File : AnyDictionary.cs
License : MIT License
Project Creator : 5minlab

internal bool TryGetValue<T>(string key, out T val, T defaultVal = default(T)) {
            if(dict == null) {
                val = defaultVal;
                return false;
            }

            object obj;
            if (dict.TryGetValue(key, out obj)) {
                if (typeof(T).IsreplacedignableFrom(obj.GetType())) {
                    val = (T)Convert.ChangeType(obj, typeof(T));
                    return (val != null);
                }
            }
            val = defaultVal;
            return false;
        }

19 View Source File : SimpleSettings.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public T GetValue<T>(string key, string def)
        {
            string ret;
            if(!values.TryGetValue(key, out ret))
            {
                if(def == null) throw new ArgumentException(string.Format("'{0}' does not exist in settings.", key));
                ret = values[key] = def;
                changed = true;
            }
            return (T) Convert.ChangeType(ret, typeof(T));
        }

19 View Source File : DmnExecutionContext.cs
License : MIT License
Project Creator : adamecr

public object EvalExpression(string expression, Type outputType)
        {
            if (string.IsNullOrWhiteSpace(expression)) throw Logger.Fatal<ArgumentException>($"{nameof(expression)} is null or empty");
            if (outputType == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(outputType)} is null");

            var interpreter = new Interpreter();
            var parameters = new List<Parameter>();
            
            //Prepare variables (as interpreter parameters)       
            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var variable in Variables.Values)
            {
                //check null variable for value type
                var varValue = variable.Value ?? variable.Type?.GetDefaultValue();

                var parameter = new Parameter(
                    variable.Name,
                    variable.Type ?? varValue?.GetType() ?? typeof(object),
                    varValue);
                parameters.Add(parameter);
            }

            //Add S-FEEL functions to the interpreter
            foreach (var customFunction in SfeelParser.CustomFunctions)
            {
                interpreter.SetFunction(customFunction.Key, customFunction.Value);
            }

            //Check parsed expression cache
            if (!ParsedExpressionsCache.TryGetValue((expression, outputType),out var parsedExpression))
            {
                parsedExpression = interpreter.Parse(expression, outputType, parameters.ToArray());
                ParsedExpressionsCache[(expression, outputType)] = parsedExpression;
            }

            //Invoke expression to evaluate
            object result;
            try
            {
                result = parsedExpression.Invoke(parameters.ToArray());
            }
            catch (Exception exception)
            {
                throw Logger.Fatal<DmnExecutorException>($"Exception while invoking the expression {expression}", exception);
            }

            //Convert the result
            object resultConverted;
            try
            {
                resultConverted = Convert.ChangeType(result, outputType);
            }
            catch (Exception exception)
            {
                throw Logger.Fatal<DmnExecutorException>($"Can't convert the expression result to {outputType.Name}", exception);
            }
            return resultConverted;
        }

19 View Source File : Amf0Writer.cs
License : MIT License
Project Creator : a1q123456

private GetBytesHandler GetBytesWrapper<T>(GetBytesHandler<T> handler)
        {
            return (object v, SerializationContext context) =>
            {
                if (v is T tv)
                {
                    handler(tv, context);
                }
                else
                {
                    handler((T)Convert.ChangeType(v, typeof(T)), context);
                }
            };
        }

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static object ChangeType(object val, Type type)
		{
			object result = null;
			if (val != null && val != DBNull.Value)
			{
				Type srcType = val.GetType();
				if (srcType == type)
				{
					result = val;
				}
				else if (val is string)
				{
					string str = val as string;
					if (type.IsEnum)
						result = Enum.Parse(type, str);
					else if (type == typeof(string[]))
						result = string.IsNullOrEmpty(str) ? null : str.Split(',');
					else if (type == typeof(Guid))
						result = new Guid(val as string);
					else
						result = System.Convert.ChangeType(str, type);
				}
				else
				{
					if (type.IsEnum)
						result = Enum.ToObject(type, val);
					else if (srcType == typeof(Guid) && type == typeof(string))
						result = val.ToString();
					else
						result = System.Convert.ChangeType(val, type);
				}
			}
			return result;
		}

19 View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH

public static T To<T>(this object s)
    {
        return (T)Convert.ChangeType(s, typeof(T));
    }

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static object ObjectFromString(string str, Type type)
		{
			object result = null;
			if (string.IsNullOrEmpty(str))
				result = type.IsValueType ? Activator.CreateInstance(type) : null;
			else if (type == typeof(Guid))
				result = new Guid(str);
			else if (type == typeof(DateTime))
				result = DateTime.Parse(str);
			else if (type == typeof(Decimal))
				result = Decimal.Parse(str);
			else if (type.IsEnum)
				result = Enum.Parse(type, str);
			else if (type.IsArray)
				result = ArrayFromString(str, type);
			else
			{
				var parse = type.GetParseMethod();
				if (parse != null)
					result = parse.Invoke(null, new object[] { str });
				else
				{
					if (type.IsValueType && !type.IsPrimitive)
						result = StructFromString(str, type);
					else
						result = System.Convert.ChangeType(str, type);
				}
			}
			return result;
		}

19 View Source File : EntityBase.cs
License : Apache License 2.0
Project Creator : aadreja

internal static bool IsKeyFieldEmpty(object id, string fieldName)
        {
            if (id is null)
                return true;
            else if (id.IsNumber())
                return Equals(id, Convert.ChangeType(0, id.GetType()));
            else if (id is Guid)
                return Equals(id, Guid.Empty);
            else
                throw new Exception(id.GetType().Name + " data type not supported for " + fieldName);
        }

19 View Source File : ChangeType.cs
License : MIT License
Project Creator : akasarto

public static T ChangeType<T>(this object @this, T defaultValue = default(T))
		{
			try
			{
				if (@this == null)
				{
					return defaultValue;
				}

				if (@this is T)
				{
					return (T)@this;
				}

				Type conversionType = typeof(T);

				// Nullables
				if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
				{
					conversionType = (new NullableConverter(conversionType)).UnderlyingType;
				}

				if (conversionType.IsEnum)
				{
					var enumStr = @this.ToString();

					// Clean the input string before attempting to convert.
					if (!string.IsNullOrWhiteSpace(enumStr))
					{
						enumStr = InvalidEnumValueChars.Replace(enumStr, string.Empty);
					}

					return (T)Enum.Parse(conversionType, enumStr, ignoreCase: true);
				}

				// String
				if (conversionType.Equals(typeof(string)))
				{
					return (T)((object)Convert.ToString(@this));
				}

				// Guid
				if (conversionType.Equals(typeof(Guid)))
				{
					var input = @this.ToString();

					if (string.IsNullOrWhiteSpace(input))
					{
						return defaultValue;
					}

					Guid output;
					if (Guid.TryParse(input, out output))
					{
						return (T)((object)output);
					}
				}

				// Bool
				if (conversionType.Equals(typeof(bool)))
				{
					return (T)((object)Convert.ToBoolean(@this));
				}

				// Datetime
				if (conversionType.Equals(typeof(DateTime)))
				{
					return (T)((object)DateTime.Parse(@this.ToString(), CultureInfo.CurrentCulture));
				}

				// TimeSpan
				if (conversionType.Equals(typeof(TimeSpan)))
				{
					return (T)((object)TimeSpan.Parse(@this.ToString(), CultureInfo.CurrentCulture));
				}

				// General
				return (T)Convert.ChangeType(@this, conversionType);
			}
			catch
			{
				return defaultValue;
			}
		}

19 View Source File : RequestObject.cs
License : MIT License
Project Creator : 0ffffffffh

public T Gereplacedem<T>(string key)
        {
            object val;

            if (!HasItem(key))
            {
                return default(T);
            }

            val = items[key.ToLower()];

            try
            {
                val = Convert.ChangeType(val, typeof(T));
            }
            catch
            {
                return default(T);
            }

            return (T)val;
        }

19 View Source File : BaseOsm.cs
License : MIT License
Project Creator : alen-smajic

protected T GetAttribute<T>(string attrName, XmlAttributeCollection attributes)
    {
        string strValue = attributes[attrName].Value;
        return (T)Convert.ChangeType(strValue, typeof(T));
    }

19 View Source File : ModuloLabelProvider.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatLabel(IComparable dataValue)
        {
            double seconds = (double)Convert.ChangeType(dataValue, typeof (double));

            double modulus = seconds%Divisor;

            return string.Format(_stringFormat, modulus);
        }

19 View Source File : ArgParser.cs
License : MIT License
Project Creator : Accelerider

public ArgParser<TArgs> Define<T>(string name, Action<TArgs, T> parser)
        {
            if (parser == null)
                throw new ArgumentNullException(nameof(parser));

            return Define(name, (o, value) =>
            {
                var typeChangedValue = (T)Convert.ChangeType(value, typeof(T));
                parser(o, typeChangedValue);
            });
        }

19 View Source File : Helper.cs
License : MIT License
Project Creator : 0ffffffffh

public static T ConvertTo<T>(string sval, T defVal = default(T))
        {
            try
            {
                return (T)Convert.ChangeType(sval, typeof(T));
            }
            catch
            {
                return defVal;
            }
        }

19 View Source File : JsonWebToken.cs
License : MIT License
Project Creator : actions

protected T TryGetValueOrDefault<T>(string key)
            {
                object ret;
                if(TryGetValue(key, out ret))
                {
                    //we have to special case DateTime
                    if (typeof(T) == typeof(DateTime))
                    {
                        return (T)(object)ConvertDateTime(ret);
                    }
                    if (typeof(T).GetTypeInfo().IsEnum && ret is string)
                    {
                        return (T)Enum.Parse(typeof(T), (string)ret);
                    }
                    return (T)Convert.ChangeType(ret, typeof(T));
                }

                return default(T);
            }

19 View Source File : AnyDictionary.cs
License : MIT License
Project Creator : 5minlab

internal T GetValue<T>(string key, T defaultVal = default(T)) {
            if(typeof(T) == typeof(string)) {
                var v = (string)Convert.ChangeType(defaultVal, typeof(string));
                return (T)Convert.ChangeType(GetString(key, v), typeof(string));
            }
            if(typeof(T) == typeof(bool)) {
                var v = (bool)Convert.ChangeType(defaultVal, typeof(bool));
                return (T)Convert.ChangeType(GetBool(key, v), typeof(bool));
            }
            if(typeof(T) == typeof(int)) {
                var v = (int)Convert.ChangeType(defaultVal, typeof(int));
                return (T)Convert.ChangeType(GetInt(key, v), typeof(int));
            }
            return defaultVal;
        }

19 View Source File : WebAppConfigurationProvider.cs
License : MIT License
Project Creator : Adoxio

private static T GetAppSetting<T>(string appSetting)
		{
			try
			{
				//We are storing the appSetting in Azure app settings section.
				//ConfigurationManager reads the setting from Azure if it's running on cloud otherwise from app.config.
				string appSettingValue = ConfigurationManager.AppSettings[appSetting];
				if (appSettingValue != null)
				{
					return (T)Convert.ChangeType(appSettingValue, typeof(T));
				}
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
			}

			return default(T);
		}

19 View Source File : SettingsReader.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static T GetSettingValue<T>(string SettingName)
		{
			try
			{
				if (SettingExists(SettingName))
				{
					T result = (T)Convert.ChangeType(ConfigurationManager.AppSettings[SettingName], typeof(T));
					if (result != null)
					{
						return result;
					}
				}
			}
			catch (Exception ex)
			{
				Logging.LogException(ex, $"{nameof(SettingsReader)}.{nameof(GetSettingValue)} threw an exception.");
			}

			return default(T);
		}

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private WriteHandler WriteHandlerWrapper<T>(WriteHandler<T> handler)
        {
            return (object obj, SerializationContext context) =>
            {
                if (obj is T tObj)
                {
                    handler(tObj, context);
                }
                else
                {
                    handler((T)Convert.ChangeType(obj, typeof(T)), context);
                }

            };
        }

19 View Source File : DarksVMSlot.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static unsafe DarksVMSlot FromObject(object obj, Type type)
        {
            if(type.IsEnum)
            {
                var elemType = Enum.GetUnderlyingType(type);
                return FromObject(Convert.ChangeType(obj, elemType), elemType);
            }

            switch(Type.GetTypeCode(type))
            {
                case TypeCode.Byte:
                    return new DarksVMSlot {u1 = (byte) obj};
                case TypeCode.SByte:
                    return new DarksVMSlot {u1 = (byte) (sbyte) obj};
                case TypeCode.Boolean:
                    return new DarksVMSlot {u1 = (byte) ((bool) obj ? 1 : 0)};

                case TypeCode.UInt16:
                    return new DarksVMSlot {u2 = (ushort) obj};
                case TypeCode.Int16:
                    return new DarksVMSlot {u2 = (ushort) (short) obj};
                case TypeCode.Char:
                    return new DarksVMSlot {u2 = (char) obj};

                case TypeCode.UInt32:
                    return new DarksVMSlot {u4 = (uint) obj};
                case TypeCode.Int32:
                    return new DarksVMSlot {u4 = (uint) (int) obj};

                case TypeCode.UInt64:
                    return new DarksVMSlot {u8 = (ulong) obj};
                case TypeCode.Int64:
                    return new DarksVMSlot {u8 = (ulong) (long) obj};

                case TypeCode.Single:
                    return new DarksVMSlot {r4 = (float) obj};
                case TypeCode.Double:
                    return new DarksVMSlot {r8 = (double) obj};

                default:
                    if(obj is Pointer)
                        return new DarksVMSlot {u8 = (ulong) Pointer.Unbox(obj)};
                    if(obj is IntPtr)
                        return new DarksVMSlot {u8 = (ulong) (IntPtr) obj};
                    if(obj is UIntPtr)
                        return new DarksVMSlot {u8 = (ulong) (UIntPtr) obj};
                    if(type.IsValueType)
                        return new DarksVMSlot {o = ValueTypeBox.Box(obj, type)};
                    return new DarksVMSlot {o = obj};
            }
        }

19 View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744

private Expression ResovleConstantExpression(string expression, Type type)
        {
            //生成指定类型的表达式
            if (expression == "null")
            {
                return Expression.Constant(null, type);
            }
            else if (type == typeof(string))
            {
                return Expression.Constant(expression.Trim('\'', '\''), type);
            }
            else
            {
                if (Nullable.GetUnderlyingType(type) == null)
                {
                    var value = Convert.ChangeType(expression, type);
                    return Expression.Constant(value, type);
                }
                else
                {
                    var undertype = Nullable.GetUnderlyingType(type);
                    var value = Convert.ChangeType(expression, undertype);
                    var expr = Expression.Constant(value, undertype);
                    return Expression.MakeUnary(ExpressionType.Convert, expr, type);
                }
            }
        }

19 View Source File : AuthorizedToken.razor.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private void SetValue(TimeSpan? time)
        {
            _updatingValue = true;

            if (!time.HasValue)
            {
                Value = default;
                ValueChanged.InvokeAsync(Value);
                TokenValueChanged.InvokeAsync(Value);
                _token.ValueString = null;
            }
            else
            {
                var timeValue = time.Value;
                var type = typeof(T);
                if (type.IsGenericType)
                {
                    type = type.GetGenericArguments()[0];
                }
                Value = (T)Convert.ChangeType(timeValue.TotalSeconds, type);
                ValueChanged.InvokeAsync(Value);
                TokenValueChanged.InvokeAsync(Value);
                _token.ValueString = timeValue.ToString(DISPLAY_FORMAT);
            }

            StateHasChanged();
            _updatingValue = false;
        }

19 View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void Show()
        {
            OpLock.Apply();
            try
            {
                Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
                

                if (!cache_prop.ContainsKey(item.GetType()))
                {
                    _reflectProps(item.GetType());
                }
                if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
                {
                    var insp = new InspectPanel();
                    currentEdit = insp;
                    int idx = 0;
                    foreach (var kv in itemProps)
                    {
                        string name = kv.Key;
                        Type propType = kv.Value.PropertyType;
                        object value = kv.Value.GetValue(item, null);
                        value = Convert.ToSingle(value);
                        ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();

                        LogProp(propType, name, value);

                        if(idx == 0)
                        {
                            insp.UpdateName(idx,name);
                            if(con is IntConstraint)
                            {
                                //Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
                            }
                            else if(con is FloatConstraint)
                            {
                                //Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            //Logger.LogDebug($"Check3 {value}-{value.GetType()}");
                            insp.UpdateValue(idx, (float)value);
                        }
                        else
                        {
                            insp.AppendPropPanel(name);
                            if (con is IntConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
                            }
                            else if (con is FloatConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            insp.UpdateValue(idx, (float)value);
                            insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));

                        }
                        //insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
                        insp.AddListener(idx, (v) => {
                            if (ItemManager.Instance.currentSelect == null)
                                return;
                            object val;
                            try
                            {
                                if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
                                {
                                    val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
                                }
                                else
                                    val = Convert.ChangeType(v, kv.Value.PropertyType);
                                ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
                            }
                            catch
                            {
                                Logger.LogError("Error occour at Inspect OnValue Chnaged");
                                Hide();
                            }
                        });
                        idx++;
                    }
                }
                else
                {
                    Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
                }
                
            }
            catch(NullReferenceException e)
            {
                Logger.LogError($"NulRef Error at Inspector.Show:{e}");
                OpLock.Undo();
            }
       
        }

19 View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static T FromXml<T>(string xml)
			where T : new()
		{
			T result = new T();
			System.Xml.XmlDoreplacedent doc = new System.Xml.XmlDoreplacedent();
			doc.LoadXml(xml);

			if (doc.HasChildNodes)
			{
				PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
				foreach (var p in props)
				{
					var node = doc.DoreplacedentElement[p.Name];
					if (node != null)
						p.SetValue(result, Convert.ChangeType(node.InnerText, p.PropertyType), null);
				}
			}
			return result;
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh

static T GetVal<T>(Dictionary<string,string> opts, string key, T failIdent)
        {
            string v;
            if (!opts.ContainsKey(key))
            {
                return failIdent;
            }

            v = opts[key];

            try
            {
                return (T)Convert.ChangeType(v, typeof(T));
            }
            catch
            {
                return failIdent;
            }
        }

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static object StructFromString(string str, Type type)
		{
			Debug.replacedert(!string.IsNullOrEmpty(str));
			Debug.replacedert(type.IsValueType);

			var flds = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (flds.Length > 0)
			{
				object result = System.Activator.CreateInstance(type);
				string[] vals = str.Split(FieldSeparator);
				for (int i = 0; i < flds.Length && i < vals.Length; ++i)
				{
					object v = ObjectFromString(vals[i], flds[i].FieldType);
					flds[i].SetValue(result, v);
				}
				return result;
			}
			else
			{
				return System.Convert.ChangeType(str, type);
			}
		}

19 View Source File : Attributes.cs
License : Apache License 2.0
Project Creator : aadreja

bool IsKeyFieldEmpty(object id, string fieldName)
        {
            if (id is null)
                return true;
            else if (id.IsNumber())
            {
                if (Equals(id, Convert.ChangeType(0, id.GetType()))) return true;
                else return false;
            }
            else if (id is Guid)
            {
                if (Equals(id, Guid.Empty)) return true;
                else return false;
            }
            else
                throw new Exception(id.GetType().Name + " data type not supported for " + fieldName);
        }

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static object ChangeType(object obj, Type type)
		{
			if (obj == null || obj == DBNull.Value)
				return null;
			if (type == typeof(object) || type == obj.GetType())
				return obj;
			if (obj is string && string.IsNullOrEmpty(obj as string))
				return null;

			object result = null;
			try
			{
				type = Nullable.GetUnderlyingType(type) ?? type;
				if (obj is string)
					result = ObjectFromString(obj as string, type);
				else if (type == typeof(string))
					result = ObjectToString(obj);
				else if (type.IsEnum)
					result = Enum.ToObject(type, obj);
				else
					result = System.Convert.ChangeType(obj, type);
			}
			catch (Exception ex) { TraceLog.WriteException(ex); throw; }
			return result;
		}

19 View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099

internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
        {
            if (valueRaw == null) return default(T);
            var type = typeof(T);
            var typename = type.ToString().TrimEnd(']');
            if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
            if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
            if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
            if (valueRaw.Length == 0) return default(T);

            string valueStr = null;
            if (type.IsValueType)
            {
                valueStr = encoding.GetString(valueRaw);
                bool isNullable = typename.StartsWith("System.Nullable`1[");
                var basename = isNullable ? typename.Substring(18) : typename;

                bool isElse = false;
                object obj = null;
                switch (basename)
                {
                    case "System.Boolean":
                        if (valueStr == "1") obj = true;
                        else if (valueStr == "0") obj = false;
                        break;
                    case "System.Byte":
                        if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
                        break;
                    case "System.Char":
                        if (valueStr.Length > 0) obj = valueStr[0];
                        break;
                    case "System.Decimal":
                        if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
                        break;
                    case "System.Double":
                        if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
                        break;
                    case "System.Single":
                        if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
                        break;
                    case "System.Int32":
                        if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
                        break;
                    case "System.Int64":
                        if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
                        break;
                    case "System.SByte":
                        if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
                        break;
                    case "System.Int16":
                        if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
                        break;
                    case "System.UInt32":
                        if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
                        break;
                    case "System.UInt64":
                        if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
                        break;
                    case "System.UInt16":
                        if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
                        break;
                    case "System.DateTime":
                        if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
                        break;
                    case "System.DateTimeOffset":
                        if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
                        break;
                    case "System.TimeSpan":
                        if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
                        break;
                    case "System.Guid":
                        if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
                        break;
                    default:
                        isElse = true;
                        break;
                }

                if (isElse == false)
                {
                    if (obj == null) return default(T);
                    return (T)obj;
                }
            }

            if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));

            if (valueStr == null) valueStr = encoding.GetString(valueRaw);
            if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
            return valueStr.ConvertTo<T>();
        }

19 View Source File : INIFile.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal T[] GetValueArray<T>(string section, string key, char separator = ',')
        {
            if (string.IsNullOrEmpty(GetValue<string>(section, key))) return new T[0];

            object val = ReadValue(section, key) ?? "";

            try
            {
                if (typeof(T) == typeof(string)) val = val.ToString().Split(separator);
                else if (typeof(T) == typeof(bool)) val = ConvertArray<bool>(val.ToString().Split(separator));
                else if (typeof(T) == typeof(int)) val = ConvertArray<int>(val.ToString().Split(separator));
                else if (typeof(T) == typeof(float)) val = ConvertArray<float>(val.ToString().Split(separator));
                else if (typeof(T) == typeof(double)) val = ConvertArray<double>(val.ToString().Split(separator));
                else if (typeof(T).IsEnum) val = ConvertArray<T>(val.ToString().Split(separator));
                //else if (CanConvertStringFrom<T>()) val = ConvertArray<T>(val.ToString().Split(separator));

                return (T[])Convert.ChangeType(val, typeof(T[]));
            }
            catch (Exception)
            {
                return default;
            }
        }

19 View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja

internal static object ToParameterValue(this object value)
        {
            if (value == null)
            {
                return DBNull.Value;
            }

            //TODO: not all needs mindatetime to be stored as null
            //if (value is DateTime && (DateTime)value == DateTime.MinValue) return DBNull.Value;

            if (value is Guid) if (Equals(value, Guid.Empty)) return DBNull.Value; else return value;
            else if (value.GetType().IsEnum) return Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()));
            else return value;
        }

19 View Source File : Uncapsulator.cs
License : MIT License
Project Creator : albahari

public override bool TryConvert (ConvertBinder binder, out object result)
        {
            if (binder.Type == typeof (IUncapsulated))
            {
                result = this;
                return true;
            }

            if (Value == null)
            {
                result = null;
                return true;
            }

            var type = Value.GetType ();
            if (!binder.Type.IsreplacedignableFrom (type))
            {
                if (binder.Type.IsNumeric () && type.IsNumeric ())
                {
                    result = Convert.ChangeType (Value, binder.Type);
                    return true;
                }
                throw new InvalidCastException ($"Cannot dynamically convert from type {type} to {binder.Type}.").Wrap ();
            }

            result = Value;
            return true;
        }

19 View Source File : Config.cs
License : MIT License
Project Creator : 0ffffffffh

private static T TryConv<T>(string v, T def)
        {
            try
            {
                return (T)Convert.ChangeType(v, typeof(T));
            }
            catch
            {
                return def;
            }
        }

19 View Source File : DialogNodeEditor.cs
License : MIT License
Project Creator : alee12131415

public string LoadCanvas(string path) {
        //SAME AS SAVE CANVAS
        try {
            //EditorSaveObject load = Resources.Load(path) as EditorSaveObject;
            EditorSaveObject load = replacedetDatabase.LoadreplacedetAtPath(path, typeof(EditorSaveObject)) as EditorSaveObject;

            //build new CP / Index
            List<ConnectionPoint> CPIndex = new List<ConnectionPoint>();
            for (int i = 0; i < load.NumberOfCP; i++) {
                CPIndex.Add(new ConnectionPoint());
            }

            //build nodes
            int spent = 0; //tracks index of used CP
            nodes = new List<Node>();
            for (int i = 0; i < load.nodeinfos.Count; i++) {
                Type t = Type.GetType(load.nodeinfos[i].type);
                ConstructorInfo ctor = t.GetConstructor(new[] { GetType(), typeof(NodeInfo) });
                Node n = (Node)Convert.ChangeType(ctor.Invoke(new object[] { this, load.nodeinfos[i] }), t);
                n.Rebuild(CPIndex.GetRange(spent, load.NodeCPIndex[i]));
                spent += load.NodeCPIndex[i];
                AddNode(n);
            }

            //build connections
            connections = new List<Connection>();
            for (int i = 0; i < load.ConnectionIndexIn.Count; i++) {
                connections.Add(new Connection(CPIndex[load.ConnectionIndexIn[i]], CPIndex[load.ConnectionIndexOut[i]], RemoveConnection));
            }

            offset = new Vector2(load.offset.x, load.offset.y);
            drag = Vector2.zero;
        } catch (Exception e) {
            return e.Message;
        }
        return null;
    }

19 View Source File : StringsOnXAxis.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatCursorLabel(IComparable dataValue)
        {
            int labelValue = (int)Convert.ChangeType(dataValue, typeof(int));
            return _labelsMap.ContainsKey(labelValue) ? _labelsMap[labelValue] : labelValue + " Not in map!";
        }

19 View Source File : AnyDictionary.cs
License : MIT License
Project Creator : 5minlab

internal T GetAt<T>(int idx) {
            if(list == null) {
                return default(T);
            }
            if(idx < 0) {
                return default(T);
            }
            if(idx >= Count) {
                return default(T);
            }
            var obj = list[idx];
            return (T)Convert.ChangeType(obj, typeof(T));
        }

19 View Source File : SqlServerIo.cs
License : MIT License
Project Creator : 0ffffffffh

public T GetValueOfColumn<T>(string name)
        {
            int colIndex;
            object v;

            try
            {
                colIndex = reader.GetOrdinal(name);
            }
            catch (IndexOutOfRangeException)
            {
                return default(T);
            }

            v = this.reader[colIndex];

            if (this.reader.IsDBNull(colIndex))
                return default(T);

            return (T)Convert.ChangeType(v, typeof(T));
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh

static T TryGetOpt<T>(string key,string [] args, T fail)
        {
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == key)
                {
                    if (i+1 != args.Length)
                    {
                        try
                        {
                            return (T)Convert.ChangeType(args[i + 1], typeof(T));
                        }
                        catch
                        {
                            return fail;
                        }
                    }
                }
            }

            return fail;
        }

19 View Source File : EnvironmentVariableReader.cs
License : MIT License
Project Creator : 1100100

public static T Get<T>(string variable, T defaultValue = default)
        {
            var value = Environment.GetEnvironmentVariable(variable);
            if (string.IsNullOrWhiteSpace(value))
                return defaultValue;

            value = value.ReplaceIpPlaceholder();

            var matches = Regex.Matches(value, "[{](.*?)[}]");
            if (matches.Count > 0)
            {
                foreach (var match in matches)
                {
                    value = value.Replace(match.ToString(), Environment.GetEnvironmentVariable(match.ToString().TrimStart('{').TrimEnd('}')));
                }
            }
            return (T)Convert.ChangeType(value, typeof(T));
        }

19 View Source File : StringExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public static List<T> StrToList<T>(this string str, char separator = ',')
        {
            var list = new List<T>();
            if (string.IsNullOrEmpty(str))
            {
                return list;
            }
            foreach (var c in str.Split(separator))
            {
                if (c.Length == 0) { continue; }

                try
                {
                    T result = (T)Convert.ChangeType(c, typeof(T));
                    if (result == null) { continue; }
                    list.Add(result);
                }
                catch (Exception)
                {

                }

            }
            return list;
        }

19 View Source File : CopyObjectExtensions.cs
License : MIT License
Project Creator : adospace

public static void CopyPropertiesTo(this object source, object dest, PropertyInfo[] destProps)
        {
            if (source.GetType().FullName != dest.GetType().FullName)
            {
                //can't copy state over a type with a different name: surely it's a different type
                return;
            }

            var sourceProps = source.GetType()
                .GetProperties()
                .Where(x => x.CanRead)
                .ToList();

            foreach (var sourceProp in sourceProps)
            {
                var targetProperty = destProps.FirstOrDefault(x => x.Name == sourceProp.Name);
                if (targetProperty != null)
                {
                    var sourceValue = sourceProp.GetValue(source, null);
                    if (sourceValue != null && sourceValue.GetType().IsEnum)
                    {
                        sourceValue = Convert.ChangeType(sourceValue, Enum.GetUnderlyingType(sourceProp.PropertyType));
                    }

                    try
                    {
                        targetProperty.SetValue(dest, sourceValue, null);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"Unable to copy property '{targetProperty.Name}' of state ({source.GetType()}) to new state after hot reload (Exception: '{DumpExceptionMessage(ex)}')");
                    }
                }
            }

        }

See More Examples