Here are the examples of the csharp api System.Convert.ChangeType(object, System.Type, System.IFormatProvider) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1107 Examples
19
View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
public T ExecuteScalar<T>(string sql, object parameter = null, int? commandTimeout = null, CommandType? commandType = null)
{
using (var cmd = Connection.CreateCommand())
{
Initialize(cmd, sql, parameter, commandTimeout, commandType);
var result = cmd.ExecuteScalar();
if (result is DBNull || result == null)
{
return default;
}
return (T)Convert.ChangeType(result, typeof(T));
}
}
19
View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
public async Task<T> ExecuteScalarAsync<T>(string sql, object parameter = null, int? commandTimeout = null, CommandType? commandType = null)
{
using (var cmd = (Connection as DbConnection).CreateCommand())
{
Initialize(cmd, sql, parameter, commandTimeout, commandType);
var result = await cmd.ExecuteScalarAsync();
if (result is DBNull || result == null)
{
return default;
}
return (T)Convert.ChangeType(result, typeof(T));
}
}
19
View Source File : DataChangedBehavior.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private static bool EvaluateComparable(IComparable leftOperand, ComparisonCondition operatorType, IComparable rightOperand)
{
object convertedOperand = null;
try
{
convertedOperand = Convert.ChangeType(rightOperand, leftOperand.GetType(), CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
catch (InvalidCastException)
{
}
if (convertedOperand == null)
{
return operatorType == ComparisonCondition.NotEqual;
}
var comparison = leftOperand.CompareTo((IComparable)convertedOperand);
switch (operatorType)
{
case ComparisonCondition.Equal:
return comparison == 0;
case ComparisonCondition.NotEqual:
return comparison != 0;
case ComparisonCondition.LessThan:
return comparison < 0;
case ComparisonCondition.LessThanOrEqual:
return comparison <= 0;
case ComparisonCondition.GreaterThan:
return comparison > 0;
case ComparisonCondition.GreaterThanOrEqual:
return comparison >= 0;
default:
return false;
}
}
19
View Source File : Types.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
private T GetSerializationItemValue<T>(SerializationInfo info, string key)
{
foreach (SerializationEntry entry in info)
{
if (entry.Name == key)
{
return (T)Convert.ChangeType(entry.Value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
}
return default(T);
}
19
View Source File : ValueMember.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private static object ParseDefaultValue(Type type, object value)
{
if(true)
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
}
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean:
case ProtoTypeCode.Byte:
case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
case ProtoTypeCode.DateTime:
case ProtoTypeCode.Decimal:
case ProtoTypeCode.Double:
case ProtoTypeCode.Int16:
case ProtoTypeCode.Int32:
case ProtoTypeCode.Int64:
case ProtoTypeCode.SByte:
case ProtoTypeCode.Single:
case ProtoTypeCode.String:
case ProtoTypeCode.UInt16:
case ProtoTypeCode.UInt32:
case ProtoTypeCode.UInt64:
case ProtoTypeCode.TimeSpan:
case ProtoTypeCode.Uri:
case ProtoTypeCode.Guid:
{
value = value + "";
}
break;
}
if (value is string)
{
string s = (string)value;
if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean: return bool.Parse(s);
case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
if (s.Length == 1) return s[0];
throw new FormatException("Single character expected: \"" + s + "\"");
case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.String: return s;
case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
case ProtoTypeCode.Uri: return s; // Uri is decorated as string
case ProtoTypeCode.Guid: return new Guid(s);
}
}
#if FEAT_IKVM
if (Helpers.IsEnum(type)) return value; // return the underlying type instead
System.Type convertType = null;
switch(Helpers.GetTypeCode(type))
{
case ProtoTypeCode.SByte: convertType = typeof(sbyte); break;
case ProtoTypeCode.Int16: convertType = typeof(short); break;
case ProtoTypeCode.Int32: convertType = typeof(int); break;
case ProtoTypeCode.Int64: convertType = typeof(long); break;
case ProtoTypeCode.Byte: convertType = typeof(byte); break;
case ProtoTypeCode.UInt16: convertType = typeof(ushort); break;
case ProtoTypeCode.UInt32: convertType = typeof(uint); break;
case ProtoTypeCode.UInt64: convertType = typeof(ulong); break;
case ProtoTypeCode.Single: convertType = typeof(float); break;
case ProtoTypeCode.Double: convertType = typeof(double); break;
case ProtoTypeCode.Decimal: convertType = typeof(decimal); break;
}
if(convertType != null) return Convert.ChangeType(value, convertType, CultureInfo.InvariantCulture);
throw new ArgumentException("Unable to process default value: " + value + ", " + type.FullName);
#else
if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
#endif
}
19
View Source File : ServiceInvoker.cs
License : MIT License
Project Creator : 99x
License : MIT License
Project Creator : 99x
public static Task Invoke(Kernel kernel, RadiumContext context)
{
DefaultResponseBody responseBody = new DefaultResponseBody();
var req = context.Request;
var res = context.Response;
string reqContentType = req.ContentType;
if (String.IsNullOrEmpty(reqContentType))
reqContentType = "application/json";
else
reqContentType = reqContentType.ToLower();
PathExecutionParams exeParams = ResourceRepository.Repo[req.Method, req.Path.Value];
try
{
if (exeParams != null)
{
Filters.FilterChainResponse chainResponse = kernel.FilterManager.ExecuteChain();
bool isSuccess = chainResponse.LastResponse !=null ? chainResponse.LastResponse.Success : true;
if (!isSuccess)
{
res.ContentType = reqContentType;
responseBody.success = false;
responseBody.result = chainResponse.LastResponse.Message;
responseBody.error = chainResponse.LastResponse.Error;
res.StatusCode = chainResponse.LastResponse.StatusCode;
}
else
{
RestResourceHandler newObj = (RestResourceHandler)Activator.CreateInstance(exeParams.ExecutionInfo.Type);
newObj.OContext = context;
newObj.DataBag = chainResponse.FilterResponse;
var exeMethod = exeParams.ExecutionInfo.Method;
List<object> activatorParams = new List<object>();
var methodParams = exeMethod.GetParameters();
foreach (var mParam in methodParams)
{
if (exeParams.Parameters.ContainsKey(mParam.Name))
{
var strValue = exeParams.Parameters[mParam.Name];
object convertedValue = Convert.ChangeType(strValue, mParam.ParameterType);
activatorParams.Add(convertedValue);
}
else
{
throw new ParameterMismatchException();
}
}
object output = exeMethod.Invoke(newObj, activatorParams.ToArray());
responseBody.success = true;
responseBody.result = output;
res.ContentType = reqContentType;
}
}
else
{
res.ContentType = reqContentType;
responseBody.success = false;
responseBody.result = "404 Not Found";
res.StatusCode = 404;
}
}
catch (Exception ex)
{
res.ContentType = reqContentType;
responseBody.success = false;
responseBody.result = ex;
res.StatusCode = 500;
}
var formatter = kernel.ResponseFormatter.GetFormatter(reqContentType);
return res.WriteAsync(formatter.Format(responseBody));
}
19
View Source File : HttpContextExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
private static T GetHeaderValueAs<T>(this HttpContext context, string headerName)
{
StringValues values;
if (context?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
{
string rawValues = values.ToString(); // writes out as Csv when there are multiple.
if (!rawValues.IsNullOrEmpty())
return (T)Convert.ChangeType(values.ToString(), typeof(T));
}
return default(T);
}
19
View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802
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 : Helper.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
internal static R Parse<R>(this object value)
{
if (value == null || value is DBNull) return default(R);
if (value is R) return (R)value;
Type type = typeof(R);
if (type.IsEnum)
{
value = Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture);
return (R)Enum.ToObject(type, value);
}
else
{
return (R)Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
}
19
View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel
License : MIT License
Project Creator : abvogel
public static void SetFieldValue(this object inputObject, string propertyName, object propertyVal)
{
Type type = inputObject.GetType();
System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);
Type propertyType = propertyInfo.PropertyType;
var targetType = IsNullableType(propertyType) ? Nullable.GetUnderlyingType(propertyType) : propertyType;
propertyVal = Convert.ChangeType(propertyVal, targetType);
propertyInfo.SetValue(inputObject, propertyVal, null);
}
19
View Source File : ConvertUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static object ChangeType(object value, Type type, IFormatProvider provider)
{
if (type.IsOfType(typeof(Nullable<>)))
{
var nullableConverter = new NullableConverter(type);
return nullableConverter.ConvertTo(value, nullableConverter.UnderlyingType);
}
return Convert.ChangeType(value, type, provider);
}
19
View Source File : DmnDecisionTable.cs
License : MIT License
Project Creator : adamecr
License : MIT License
Project Creator : adamecr
private static PositiveRulesCollectValues CalculatePositiveRulesCollectValues(
IEnumerable<DmnDecisionTableRule> positiveRules,
DmnDecisionTableRuleExecutionResults results)
{
double sum = 0;
var min = double.MaxValue;
var max = double.MinValue;
var distinctValues = new List<double>();
foreach (var positiveRule in positiveRules)
{
var valueRaw = results.GetResult(positiveRule, positiveRule.Outputs[0])?.Value;
if (valueRaw == null) continue; //ignore null results/values
double value;
var isBool = positiveRule.Outputs[0].Output.Variable.Type == typeof(bool);
if (isBool)
{
value = (bool)valueRaw ? 1 : 0;
}
else
{
value = (double)Convert.ChangeType(valueRaw, typeof(double));
}
sum += value;
if (value < min) min = value;
if (value > max) max = value;
if (!distinctValues.Contains(value))
{
distinctValues.Add(value);
}
}
var count = distinctValues.Count;
return new PositiveRulesCollectValues(sum, min, max, count);
}
19
View Source File : SettingsSetterViewController.cs
License : MIT License
Project Creator : Aeroluna
License : MIT License
Project Creator : Aeroluna
internal void Init(StartStandardLevelParameters startParameters, MenuTransitionsHelper menuTransitionsHelper)
{
if (startParameters.DifficultyBeatmap.beatmapData is CustomBeatmapData customBeatmapData)
{
Dictionary<string, object?>? settings = customBeatmapData.beatmapCustomData.Get<Dictionary<string, object?>>("_settings");
if (settings != null)
{
_contents.Clear();
_modifiedParameters = startParameters;
Dictionary<string, object?>? jsonPlayerOptions = settings.Get<Dictionary<string, object?>>("_playerOptions");
if (jsonPlayerOptions != null)
{
PlayerSpecificSettings playerSettings = startParameters.PlayerSpecificSettings;
List<Dictionary<string, object>> settablePlayerSettings = SettingSetterSettableSettingsManager.SettingsTable["_playerOptions"];
PlayerSpecificSettings modifiedPlayerSettings = playerSettings.CopyWith();
foreach (Dictionary<string, object> settablePlayerSetting in settablePlayerSettings)
{
string name = (string)settablePlayerSetting["_name"];
string fieldName = (string)settablePlayerSetting["_fieldName"];
object? json = jsonPlayerOptions.Get<object>(fieldName);
if (json != null)
{
FieldInfo field = typeof(PlayerSpecificSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
object activeValue = field.GetValue(playerSettings);
if (json is string jsonString)
{
json = Enum.Parse(typeof(EnvironmentEffectsFilterPreset), jsonString);
}
else if (json is IConvertible)
{
json = Convert.ChangeType(json, activeValue.GetType());
}
if (!json.Equals(activeValue))
{
_contents.Add(new ListObject($"[Player Options] {name}", $"{activeValue} > {json}"));
field.SetValue(modifiedPlayerSettings, json);
}
}
}
_modifiedParameters.PlayerSpecificSettings = modifiedPlayerSettings;
}
Dictionary<string, object?>? jsonModifiers = settings.Get<Dictionary<string, object?>>("_modifiers");
if (jsonModifiers != null)
{
GameplayModifiers gameplayModifiers = startParameters.GameplayModifiers;
List<Dictionary<string, object>> settableGameplayModifiers = SettingSetterSettableSettingsManager.SettingsTable["_modifiers"];
GameplayModifiers modifiedGameplayModifiers = gameplayModifiers.CopyWith();
foreach (Dictionary<string, object> settableGameplayModifier in settableGameplayModifiers)
{
string name = (string)settableGameplayModifier["_name"];
string fieldName = (string)settableGameplayModifier["_fieldName"];
object? json = jsonModifiers.Get<object>(fieldName);
if (json != null)
{
FieldInfo field = typeof(GameplayModifiers).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
object activeValue = field.GetValue(gameplayModifiers);
if (json is string jsonString)
{
switch (fieldName)
{
case "_energyType":
json = Enum.Parse(typeof(GameplayModifiers.EnergyType), jsonString);
break;
case "_enabledObstacleType":
json = Enum.Parse(typeof(GameplayModifiers.EnabledObstacleType), jsonString);
break;
case "_songSpeed":
json = Enum.Parse(typeof(GameplayModifiers.SongSpeed), jsonString);
break;
}
}
else if (json is IConvertible)
{
json = Convert.ChangeType(json, activeValue.GetType());
}
if (!json.Equals(activeValue))
{
_contents.Add(new ListObject($"[Modifiers] {name}", $"{activeValue} > {json}"));
field.SetValue(modifiedGameplayModifiers, json);
}
}
}
_modifiedParameters.GameplayModifiers = modifiedGameplayModifiers;
}
Dictionary<string, object?>? jsonEnvironments = settings.Get<Dictionary<string, object?>>("_environments");
if (jsonEnvironments != null)
{
OverrideEnvironmentSettings? environmentOverrideSettings = startParameters.OverrideEnvironmentSettings;
if (environmentOverrideSettings != null)
{
Dictionary<string, object> settableEnvironmentSetting = SettingSetterSettableSettingsManager.SettingsTable["_environments"].First();
string name = (string)settableEnvironmentSetting["_name"];
string fieldName = (string)settableEnvironmentSetting["_fieldName"];
bool activeValue = environmentOverrideSettings.overrideEnvironments;
bool? json = jsonEnvironments.Get<bool>(fieldName);
if (json != null && json != activeValue)
{
_contents.Add(new ListObject($"[Environments] {name}", $"{activeValue} > {json}"));
// copy fields from original overrideenvironmentsettings to our new copy
OverrideEnvironmentSettings modifiedOverrideEnvironmentSettings = new OverrideEnvironmentSettings();
modifiedOverrideEnvironmentSettings.SetField("_data", environmentOverrideSettings.GetField<Dictionary<EnvironmentTypeSO, EnvironmentInfoSO>, OverrideEnvironmentSettings>("_data"));
modifiedOverrideEnvironmentSettings.overrideEnvironments = json.Value;
_modifiedParameters.OverrideEnvironmentSettings = modifiedOverrideEnvironmentSettings;
}
}
}
Dictionary<string, object?>? jsonColors = settings.Get<Dictionary<string, object?>>("_colors");
if (jsonColors != null)
{
ColorSchemesSettings? colorSchemesSettings = OverrideColorScheme;
if (colorSchemesSettings != null)
{
Dictionary<string, object> settableColorSetting = SettingSetterSettableSettingsManager.SettingsTable["_colors"].First();
string name = (string)settableColorSetting["_name"];
string fieldName = (string)settableColorSetting["_fieldName"];
bool activeValue = colorSchemesSettings.overrideDefaultColors;
bool? json = jsonColors.Get<bool>(fieldName);
if (json != null && json != activeValue)
{
_contents.Add(new ListObject($"[Colors] {name}", $"{activeValue} > {json}"));
_modifiedParameters.OverrideColorScheme = json.Value ? colorSchemesSettings.GetOverrideColorScheme() : null;
}
}
}
_modifiedMainSettings = null;
_cachedMainSettings = null;
Dictionary<string, object?>? jsonGraphics = settings.Get<Dictionary<string, object?>>("_graphics");
if (jsonGraphics != null)
{
MainSettingsModelSO mainSettingsModel = MainSettings;
List<Dictionary<string, object>> settableGraphicsSettings = SettingSetterSettableSettingsManager.SettingsTable["_graphics"];
_cachedMainSettings = new SettableMainSettings(
mainSettingsModel.mirrorGraphicsSettings,
mainSettingsModel.mainEffectGraphicsSettings,
mainSettingsModel.smokeGraphicsSettings,
mainSettingsModel.burnMarkTrailsEnabled,
mainSettingsModel.screenDisplacementEffectsEnabled,
mainSettingsModel.maxShockwaveParticles);
_modifiedMainSettings = _cachedMainSettings with { };
foreach (Dictionary<string, object> settableGraphicSetting in settableGraphicsSettings)
{
string name = (string)settableGraphicSetting["_name"];
string fieldName = (string)settableGraphicSetting["_fieldName"];
object? json = jsonGraphics.Get<object>(fieldName);
if (json != null)
{
// substring is to remove underscore
object valueSO = typeof(MainSettingsModelSO).GetField(fieldName.Substring(1), BindingFlags.Instance | BindingFlags.Public).GetValue(mainSettingsModel);
object activeValue = valueSO switch
{
BoolSO boolSO => boolSO.value,
IntSO intSO => intSO.value,
_ => throw new InvalidOperationException($"How the hell did you reach this? [{valueSO.GetType()}]"),
};
if (json is IConvertible)
{
json = Convert.ChangeType(json, activeValue.GetType());
}
if (!json.Equals(activeValue))
{
_contents.Add(new ListObject($"[Graphics] {name}", $"{activeValue} > {json}"));
typeof(SettableMainSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(_modifiedMainSettings, json);
}
}
}
}
_settableSettingsToSet = null;
foreach (KeyValuePair<string, Dictionary<string, ISettableSetting>> groupSettingPair in SettingSetterSettableSettingsManager.SettableSettings)
{
Dictionary<string, object?>? jsonGroup = settings.Get<Dictionary<string, object?>>(groupSettingPair.Key);
if (jsonGroup != null)
{
_settableSettingsToSet = new List<Tuple<ISettableSetting, object>>();
foreach (KeyValuePair<string, ISettableSetting> settableSettingPair in groupSettingPair.Value)
{
object? json = jsonGroup.Get<object>(settableSettingPair.Key);
ISettableSetting settableSetting = settableSettingPair.Value;
object activeValue = settableSetting.TrueValue;
if (json != null && !json.Equals(activeValue))
{
_contents.Add(new ListObject($"[{settableSetting.GroupName}] {settableSetting.FieldName}", $"{activeValue} > {json}"));
_settableSettingsToSet.Add(new Tuple<ISettableSetting, object>(settableSetting, json));
}
}
}
}
if (_contents.Any())
{
if (_contentObject != null)
{
Destroy(_contentObject);
}
DoPresent = true;
_defaultParameters = startParameters;
_menuTransitionsHelper = menuTransitionsHelper;
_presentViewController(ActiveFlowCoordinator, this, null, AnimationDirection.Horizontal, false);
BeatSaberMarkupLanguage.BSMLParser.instance.Parse(ContentBSML, gameObject, this);
return;
}
}
}
19
View Source File : Types.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private T GetSerializationItemValue<T>(SerializationInfo info, string key) {
foreach (SerializationEntry entry in info) {
if (entry.Name == key) {
return (T)Convert.ChangeType(entry.Value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
}
return default(T);
}
19
View Source File : ConfigurationExtensions.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
private static void HydrateInstance(ref object config, ConfigSection section)
{
var props = config.GetType().GetProperties();
foreach (var prop in props)
{
// Must have a set method for this to work, otherwise continue on
if (prop.SetMethod == null)
continue;
var entry = section.GetValue(prop.Name);
object? value = null;
if (typeof(string) == prop.PropertyType)
{
// We do NOT want to override value if nothing was provided
if(!string.IsNullOrEmpty(entry))
prop.SetValue(config, entry);
continue;
}
// We need to address collections a bit differently
// They can come in the form of "root:section:name" with a string representation OR
// "root:section:name:0" <--- this is not detectable when checking the above path
if (typeof(IEnumerable).IsreplacedignableFrom(prop.PropertyType))
{
value = string.IsNullOrEmpty(section.GetValue(prop.Name))
? section.Config
.GetSection(section.GetPath(prop.Name)).Get(prop.PropertyType)
: Newtonsoft.Json.JsonConvert.DeserializeObject(entry, prop.PropertyType);
if (value == null)
continue;
prop.SetValue(config, value);
}
// From this point onward we require the 'entry' value to have something useful
if (string.IsNullOrEmpty(entry))
continue;
try
{
// Primitive types are simple to convert
if (prop.PropertyType.IsPrimitive)
value = Convert.ChangeType(entry, prop.PropertyType);
else
{
// The following types require a different approach
if (prop.PropertyType.IsEnum)
value = Enum.Parse(prop.PropertyType, entry);
else if (typeof(TimeSpan) == prop.PropertyType)
value = TimeSpan.Parse(entry);
else if (typeof(DateTime) == prop.PropertyType)
value = DateTime.Parse(entry);
else if (typeof(DateTimeOffset) == prop.PropertyType)
value = DateTimeOffset.Parse(entry);
}
// Update value within our config instance
prop.SetValue(config, value);
}
catch (Exception ex)
{
Console.Error.WriteLine(
$"Unable to convert value of '{entry}' to type '{prop.PropertyType.Name}' for prop '{prop.Name}' in config '{config.GetType().Name}'\n\t\t{ex.Message}");
}
}
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
internal static U Convert<T, U>(this T token) where T : JToken
{
if (token == null)
{
return default(U);
}
if (token is U
// don't want to cast JValue to its interfaces, want to get the internal value
&& typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable))
{
// HACK
return (U)(object)token;
}
else
{
JValue value = token as JValue;
if (value == null)
{
throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T)));
}
if (value.Value is U)
{
return (U)value.Value;
}
Type targetType = typeof(U);
if (ReflectionUtils.IsNullableType(targetType))
{
if (value.Value == null)
{
return default(U);
}
targetType = Nullable.GetUnderlyingType(targetType);
}
return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture);
}
}
19
View Source File : EnumUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public static IList<T> GetFlagsValues<T>(T value) where T : struct
{
Type enumType = typeof(T);
if (!enumType.IsDefined(typeof(FlagsAttribute), false))
{
throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType));
}
Type underlyingType = Enum.GetUnderlyingType(value.GetType());
ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
IList<EnumValue<ulong>> enumNameValues = GetNamesAndValues<T>();
IList<T> selectedFlagsValues = new List<T>();
foreach (EnumValue<ulong> enumNameValue in enumNameValues)
{
if ((num & enumNameValue.Value) == enumNameValue.Value && enumNameValue.Value != 0)
{
selectedFlagsValues.Add((T)Convert.ChangeType(enumNameValue.Value, underlyingType, CultureInfo.CurrentCulture));
}
}
if (selectedFlagsValues.Count == 0 && enumNameValues.SingleOrDefault(v => v.Value == 0) != null)
{
selectedFlagsValues.Add(default(T));
}
return selectedFlagsValues;
}
19
View Source File : EnumUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public static IList<EnumValue<TUnderlyingType>> GetNamesAndValues<TUnderlyingType>(Type enumType) where TUnderlyingType : struct
{
if (enumType == null)
{
throw new ArgumentNullException(nameof(enumType));
}
if (!enumType.IsEnum())
{
throw new ArgumentException("Type {0} is not an Enum.".FormatWith(CultureInfo.InvariantCulture, enumType), nameof(enumType));
}
IList<object> enumValues = GetValues(enumType);
IList<string> enumNames = GetNames(enumType);
IList<EnumValue<TUnderlyingType>> nameValues = new List<EnumValue<TUnderlyingType>>();
for (int i = 0; i < enumValues.Count; i++)
{
try
{
nameValues.Add(new EnumValue<TUnderlyingType>(enumNames[i], (TUnderlyingType)Convert.ChangeType(enumValues[i], typeof(TUnderlyingType), CultureInfo.CurrentCulture)));
}
catch (OverflowException e)
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}",
Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(enumValues[i], CultureInfo.InvariantCulture)), e);
}
}
return nameValues;
}
19
View Source File : JsonSerializerInternalReader.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType)
{
if (targetType == null)
{
return value;
}
Type valueType = ReflectionUtils.GetObjectType(value);
// type of value and type of target don't match
// attempt to convert value's type to target's type
if (valueType != targetType)
{
if (value == null && contract.IsNullable)
{
return null;
}
try
{
if (contract.IsConvertable)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (contract.IsEnum)
{
if (value is string)
{
return Enum.Parse(contract.NonNullableUnderlyingType, value.ToString(), true);
}
if (ConvertUtils.IsInteger(primitiveContract.TypeCode))
{
return Enum.ToObject(contract.NonNullableUnderlyingType, value);
}
}
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
if (value is BigInteger)
{
return ConvertUtils.FromBigInteger((BigInteger)value, contract.NonNullableUnderlyingType);
}
#endif
// this won't work when converting to a custom IConvertible
return Convert.ChangeType(value, contract.NonNullableUnderlyingType, culture);
}
return ConvertUtils.ConvertOrCast(value, culture, contract.NonNullableUnderlyingType);
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(value), targetType), ex);
}
}
return value;
}
19
View Source File : JsonFormatterConverter.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private T GetTokenValue<T>(object value)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JValue v = (JValue)value;
return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture);
}
19
View Source File : ConvertUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public static object FromBigInteger(BigInteger i, Type targetType)
{
if (targetType == typeof(decimal))
{
return (decimal)i;
}
if (targetType == typeof(double))
{
return (double)i;
}
if (targetType == typeof(float))
{
return (float)i;
}
if (targetType == typeof(ulong))
{
return (ulong)i;
}
if (targetType == typeof(bool))
{
return i != 0;
}
try
{
return System.Convert.ChangeType((long)i, targetType, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
throw new InvalidOperationException("Can not convert from BigInteger to {0}.".FormatWith(CultureInfo.InvariantCulture, targetType), ex);
}
}
19
View Source File : ConvertUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value)
{
if (initialValue == null)
{
throw new ArgumentNullException(nameof(initialValue));
}
if (ReflectionUtils.IsNullableType(targetType))
{
targetType = Nullable.GetUnderlyingType(targetType);
}
Type initialType = initialValue.GetType();
if (targetType == initialType)
{
value = initialValue;
return ConvertResult.Success;
}
// use Convert.ChangeType if both types are IConvertible
if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType))
{
if (targetType.IsEnum())
{
if (initialValue is string)
{
value = Enum.Parse(targetType, initialValue.ToString(), true);
return ConvertResult.Success;
}
else if (IsInteger(initialValue))
{
value = Enum.ToObject(targetType, initialValue);
return ConvertResult.Success;
}
}
value = System.Convert.ChangeType(initialValue, targetType, culture);
return ConvertResult.Success;
}
#if !NET20
if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
{
value = new DateTimeOffset((DateTime)initialValue);
return ConvertResult.Success;
}
#endif
if (initialValue is byte[] && targetType == typeof(Guid))
{
value = new Guid((byte[])initialValue);
return ConvertResult.Success;
}
if (initialValue is Guid && targetType == typeof(byte[]))
{
value = ((Guid)initialValue).ToByteArray();
return ConvertResult.Success;
}
string s = initialValue as string;
if (s != null)
{
if (targetType == typeof(Guid))
{
value = new Guid(s);
return ConvertResult.Success;
}
if (targetType == typeof(Uri))
{
value = new Uri(s, UriKind.RelativeOrAbsolute);
return ConvertResult.Success;
}
if (targetType == typeof(TimeSpan))
{
value = ParseTimeSpan(s);
return ConvertResult.Success;
}
if (targetType == typeof(byte[]))
{
value = System.Convert.FromBase64String(s);
return ConvertResult.Success;
}
if (targetType == typeof(Version))
{
Version result;
if (VersionTryParse(s, out result))
{
value = result;
return ConvertResult.Success;
}
value = null;
return ConvertResult.NoValidConversion;
}
if (typeof(Type).IsreplacedignableFrom(targetType))
{
value = Type.GetType(s, true);
return ConvertResult.Success;
}
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
if (targetType == typeof(BigInteger))
{
value = ToBigInteger(initialValue);
return ConvertResult.Success;
}
if (initialValue is BigInteger)
{
value = FromBigInteger((BigInteger)initialValue, targetType);
return ConvertResult.Success;
}
#endif
#if !(PORTABLE40 || PORTABLE)
// see if source or target types have a TypeConverter that converts between the two
TypeConverter toConverter = GetConverter(initialType);
if (toConverter != null && toConverter.CanConvertTo(targetType))
{
value = toConverter.ConvertTo(null, culture, initialValue, targetType);
return ConvertResult.Success;
}
TypeConverter fromConverter = GetConverter(targetType);
if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
{
value = fromConverter.ConvertFrom(null, culture, initialValue);
return ConvertResult.Success;
}
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
// handle DBNull and INullable
if (initialValue == DBNull.Value)
{
if (ReflectionUtils.IsNullable(targetType))
{
value = EnsureTypereplacedignable(null, initialType, targetType);
return ConvertResult.Success;
}
// cannot convert null to non-nullable
value = null;
return ConvertResult.CannotConvertNull;
}
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
if (initialValue is INullable)
{
value = EnsureTypereplacedignable(ToValue((INullable)initialValue), initialType, targetType);
return ConvertResult.Success;
}
#endif
if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
{
value = null;
return ConvertResult.NotInstantiableType;
}
value = null;
return ConvertResult.NoValidConversion;
}
19
View Source File : ImguiUtil.cs
License : GNU Affero General Public License v3.0
Project Creator : akira0245
License : GNU Affero General Public License v3.0
Project Creator : akira0245
public static bool EnumCombo<TEnum>(string label, ref TEnum @enum, string[] toolTips, ImGuiComboFlags flags = ImGuiComboFlags.None, bool showValue = false) where TEnum : struct, Enum
{
var ret = false;
var previewValue = showValue ? $"{@enum.ToString().Localize()} ({Convert.ChangeType(@enum, @enum.GetTypeCode())})" : @enum.ToString().Localize();
if (BeginCombo(label, previewValue, flags))
{
var values = Enum.GetValues<TEnum>();
for (var i = 0; i < values.Length; i++)
try
{
PushID(i);
var s = showValue
? $"{values[i].ToString().Localize()} ({Convert.ChangeType(values[i], values[i].GetTypeCode())})"
: values[i].ToString().Localize();
if (Selectable(s, values[i].Equals(@enum)))
{
ret = true;
@enum = values[i];
}
if (IsItemHovered())
{
ToolTip(toolTips[i].Localize());
}
PopID();
}
catch (Exception e)
{
PluginLog.Error(e.ToString());
}
EndCombo();
}
return ret;
}
19
View Source File : ImguiUtil.cs
License : GNU Affero General Public License v3.0
Project Creator : akira0245
License : GNU Affero General Public License v3.0
Project Creator : akira0245
public static bool EnumCombo<TEnum>(string label, ref TEnum @enum, ImGuiComboFlags flags = ImGuiComboFlags.None, bool showValue = false) where TEnum : struct, Enum
{
var ret = false;
var previewValue = showValue ? $"{@enum} ({Convert.ChangeType(@enum, @enum.GetTypeCode())})" : @enum.ToString();
if (BeginCombo(label, previewValue, flags))
{
var values = Enum.GetValues<TEnum>();
for (var i = 0; i < values.Length; i++)
try
{
PushID(i);
var s = showValue
? $"{values[i]} ({Convert.ChangeType(values[i], values[i].GetTypeCode())})"
: values[i].ToString();
if (Selectable(s, values[i].Equals(@enum)))
{
ret = true;
@enum = values[i];
}
PopID();
}
catch (Exception e)
{
PluginLog.Error(e.ToString());
}
EndCombo();
}
return ret;
}
19
View Source File : SerrializableObject.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
public void Deserialize()
{
if (String.IsNullOrEmpty(serializedType))
{
Debug.LogError("Can't deserialize the object from null type");
return;
}
Type type = Type.GetType(serializedType);
if (type.IsPrimitive)
{
if (string.IsNullOrEmpty(serializedValue))
value = Activator.CreateInstance(type);
else
value = Convert.ChangeType(serializedValue, type, CultureInfo.InvariantCulture);
}
else if (typeof(UnityEngine.Object).IsreplacedignableFrom(type))
{
ObjectWrapper obj = new ObjectWrapper();
JsonUtility.FromJsonOverwrite(serializedValue, obj);
value = obj.value;
}
else if (type == typeof(string))
value = serializedValue.Length > 1 ? serializedValue.Substring(1, serializedValue.Length - 2).Replace("\\\"", "\"") : "";
else
{
try {
value = Activator.CreateInstance(type);
JsonUtility.FromJsonOverwrite(serializedValue, value);
} catch (Exception e){
Debug.LogError(e);
Debug.LogError("Can't serialize type " + serializedType);
}
}
}
19
View Source File : JSON.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private object ChangeType(object value, Type conversionType)
{
if (conversionType == typeof(int))
{
string s = value as string;
if (s == null)
return (int)((long)value);
else
return JsonHelper.CreateInteger(s, 0, s.Length);
}
else if (conversionType == typeof(long))
{
string s = value as string;
if (s == null)
return (long)value;
else
return JsonHelper.CreateLong(s, 0, s.Length);
}
else if (conversionType == typeof(string))
return (string)value;
else if (conversionType.IsEnum)
return JsonHelper.CreateEnum(conversionType, value);
else if (conversionType == typeof(DateTime))
return JsonHelper.CreateDateTime((string)value, _params.UseUTCDateTime);
else if (conversionType == typeof(DateTimeOffset))
return JsonHelper.CreateDateTimeOffset((string)value);
else if (Reflection.Instance.IsTypeRegistered(conversionType))
return Reflection.Instance.CreateCustom((string)value, conversionType);
// 8-30-2014 - James Brooks - Added code for nullable types.
if (JsonHelper.IsNullable(conversionType))
{
if (value == null)
return value;
conversionType = JsonHelper.UnderlyingTypeOf(conversionType);
}
// 8-30-2014 - James Brooks - Nullable Guid is a special case so it was moved after the "IsNullable" check.
if (conversionType == typeof(Guid))
return JsonHelper.CreateGuid((string)value);
// 2016-04-02 - Enrico Padovani - proper conversion of byte[] back from string
if (conversionType == typeof(byte[]))
return Convert.FromBase64String((string)value);
if (conversionType == typeof(TimeSpan))
return new TimeSpan((long)value);
return Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
}
19
View Source File : ServiceExecutor.cs
License : MIT License
Project Creator : alexandredenes
License : MIT License
Project Creator : alexandredenes
private object[] CreateParams(ParameterInfo[] parameterInfo, RequestMessage requestMessage)
{
object[] retVal = new object[parameterInfo.Length];
for(int x=0;x<retVal.Length;x++)
{
retVal[x] = Convert.ChangeType(requestMessage.Params[parameterInfo[x].Name],parameterInfo[x].ParameterType);
}
return retVal;
}
19
View Source File : ReflectionHelper.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static void FillList<T>(IEnumerable source, string propertyName, IList<T> list)
{
PropertyInfo pi = null;
Type t = null;
foreach (var o in source)
{
if (pi == null || o.GetType() != t)
{
t = o.GetType();
pi = t.GetProperty(propertyName);
if (pi == null)
{
throw new InvalidOperationException(
string.Format("Could not find field {0} on type {1}", propertyName, t));
}
}
var v = pi.GetValue(o, null);
var value = (T)Convert.ChangeType(v, typeof(T), CultureInfo.InvariantCulture);
list.Add(value);
}
}
19
View Source File : NumericProperty.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
public override bool TryValidate(IMessageBoxService messageBoxService)
{
try
{
Convert.ChangeType(Value, typeof(T));
}
catch
{
messageBoxService.ShowError($"'{Name.TrimEnd(':')}' must be a valid {typeof(T).Name}.");
return false;
}
return base.TryValidate(messageBoxService);
}
19
View Source File : NumericProperty.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
public override void Save(XmlDoreplacedent xmlDoc, XmlNode newNode)
{
if (!string.IsNullOrEmpty(Value))
{
T value = (T)Convert.ChangeType(Value, typeof(T));
if (!Equals(value, mDefaultValue))
{
xmlDoc.CreateElementWithValueAttribute(ElementName, value.ToString()).AppendTo(newNode);
}
}
}
19
View Source File : ConverterHelper.cs
License : MIT License
Project Creator : alexvolchetsky
License : MIT License
Project Creator : alexvolchetsky
public static void WriteItem<T>(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
object newValue = null;
if (value != null)
{
newValue = Convert.ChangeType(value, value.GetType(), CultureInfo.InvariantCulture);
}
JsonSerializer.Serialize(writer, newValue, options);
}
19
View Source File : Reflection.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public static object ConvertObject(object obj, Type type)
{
var t = GetObjectType(type);
if(obj == null)
{
return GetDefault(t);
}
if(t.IsEnum)
{
obj = Enum.Parse(t, obj is string value ? value : obj.ToString(), false);
}
if(t == typeof(string))
{
if(obj is string convertObject)
{
return convertObject;
}
var mi = obj.GetType().GetMethods().SingleOrDefault(m => m.Name == "ToString" && !m.GetMethodParameters().Any());
return mi?.Invoke(obj, Array.Empty<object>());
}
if((obj is string s) && t == typeof(char[]))
{
return s.Split();
}
if(t.IsArray)
{
if(obj is Array arrSrc)
{
var arrDest = (Array)CreateArray(t.GetElementType(), arrSrc.Length);
Array.Copy(arrSrc, arrDest, arrSrc.Length);
return arrDest;
}
}
if(t == typeof(object))
{
return obj;
}
if(obj is not string o)
{
return Convert.ChangeType(obj, t);
}
if(t == typeof(bool))
{
if(short.TryParse(o, out var i))
{
return i != 0;
}
return bool.Parse(o);
}
if(t == typeof(decimal) || t == typeof(float))
{
var types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), t.MakeByRefType() };
var args = new[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "," }, GetDefault(t) };
if((bool)t.GetMethod("TryParse", types)?.Invoke(null, args)!)
{
return args[3];
}
types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider) };
args = new object[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "." } };
return t.GetMethod("Parse", types)?.Invoke(null, args);
}
if(t == typeof(long)
|| t == typeof(ulong)
|| t == typeof(int)
|| t == typeof(uint)
|| t == typeof(short)
|| t == typeof(ushort)
|| t == typeof(byte)
|| t == typeof(sbyte)
|| t == typeof(char))
{
return t.GetMethod("Parse", new[] { typeof(string) })?.Invoke(null, new object[] {o});
}
if(t == typeof(DateTime))
{
return DateTime.TryParse(o, CultureInfo.GetCultureInfo("ru-RU"), DateTimeStyles.replacedumeLocal, out var dt) ? dt : DateTime.Parse(o, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.replacedumeLocal);
}
return Convert.ChangeType(o, t);
}
19
View Source File : ModConfig.cs
License : MIT License
Project Creator : amazingalek
License : MIT License
Project Creator : amazingalek
private T GetSettingsValue<T>(string key, object setting)
{
try
{
var type = typeof(T);
var value = setting is JObject objectValue ? objectValue["value"] : setting;
return type.IsEnum ? ConvertToEnum<T>(value) : (T)Convert.ChangeType(value, type);
}
catch (Exception ex)
{
Debug.LogError($"Error when getting setting {key}: " + ex.Message);
return default;
}
}
19
View Source File : SettingForm.cs
License : MIT License
Project Creator : AmazingDM
License : MIT License
Project Creator : AmazingDM
private void BindTextBox<T>(TextBox control, Func<T, bool> check, Action<T> save, object value)
{
control.Text = value.ToString();
_checkActions.Add(control, s =>
{
try
{
return check.Invoke((T) Convert.ChangeType(s, typeof(T)));
}
catch
{
return false;
}
});
_saveActions.Add(control, c => save.Invoke((T) Convert.ChangeType(((TextBox) c).Text, typeof(T))));
}
19
View Source File : IMFAttributes.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
public unsafe T Get<T>(Guid guidKey)
{
// Perform conversions to supported types
// int
// long
// string
// byte[]
// double
// ComObject
// Guid
if (typeof(T) == typeof(int) || typeof(T) == typeof(bool) || typeof(T) == typeof(byte) || typeof(T) == typeof(uint) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort) || typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
{
return (T)Convert.ChangeType(GetInt(guidKey), typeof(T));
}
if (typeof(T).IsEnum)
{
return (T)Enum.ToObject(typeof(T), GetInt(guidKey));
}
if (typeof(T) == typeof(IntPtr))
{
return (T)(object)new IntPtr((long)GetLong(guidKey));
}
if (typeof(T) == typeof(UIntPtr))
{
return (T)(object)new UIntPtr(GetLong(guidKey));
}
if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong))
{
return (T)Convert.ChangeType(GetLong(guidKey), typeof(T));
}
if (typeof(T) == typeof(Guid))
{
return (T)(object)GetGUID(guidKey);
}
if (typeof(T) == typeof(string))
{
int length = GetStringLength(guidKey);
char* wstr = stackalloc char[length + 1];
GetString(guidKey, new IntPtr(wstr), length + 1, IntPtr.Zero);
return (T)(object)Marshal.PtrToStringUni(new IntPtr(wstr));
}
if (typeof(T) == typeof(double) || typeof(T) == typeof(float))
{
return (T)Convert.ChangeType(GetDouble(guidKey), typeof(T));
}
if (typeof(T) == typeof(byte[]))
{
int length = GetBlobSize(guidKey);
byte[] buffer = new byte[length];
fixed (void* pBuffer = buffer)
{
GetBlob(guidKey, (IntPtr)pBuffer, buffer.Length, IntPtr.Zero);
}
return (T)(object)buffer;
}
if (typeof(T).IsValueType)
{
int length = GetBlobSize(guidKey);
if (length != Unsafe.SizeOf<T>())
{
throw new ArgumentException("Size of the structure doesn't match the size of stored value");
}
var value = default(T);
GetBlob(guidKey, (IntPtr)Unsafe.AsPointer(ref value), Unsafe.SizeOf<T>(), IntPtr.Zero);
return value;
}
if (typeof(T) == typeof(ComObject))
{
IntPtr ptr = GetUnknown(guidKey, typeof(IUnknown).GUID);
return (T)(object)new ComObject(ptr);
}
if (typeof(T).IsSubclreplacedOf(typeof(ComObject)))
{
IntPtr ptr = GetUnknown(guidKey, typeof(T).GUID);
return (T)Activator.CreateInstance(typeof(T), ptr);
}
throw new ArgumentException("The type of the value is not supported");
}
19
View Source File : DbQueryProcessor.cs
License : MIT License
Project Creator : amolines
License : MIT License
Project Creator : amolines
public async Task<IQueryResponse> ProcessAsync(QueryRequest<TCriteria> request)
{
var query = CreateQuery(request.Criteria);
try
{
var data = await _repository.ExecuteReaderAsync(query);
foreach (var root in data)
{
if (request.Criteria.Embeds != null && request.Criteria.Embeds.Any())
SetEmbeds(request.Criteria.Embeds, root);
}
QueryResponse<TOut> result = null;
if (!request.Criteria.IsSlice && !request.Criteria.IsPaginate)
{
result = new QueryResponse<TOut>(data);
}
else
{
var total = await _repository.ExecuteScalarAsync(query.SqlCount);
var value = (long)Convert.ChangeType(total, typeof(long));
if (request.Criteria.Paginate != null)
{
result = new PaginateQueryResponse<TOut>(data, new PaginateHeader(request.Criteria, value));
}
else
{
result = new SliceQueryResponse<TOut>(data, new SliceHeader(value));
}
}
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
19
View Source File : EnumMarshaler.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
public void MarshalObject(object value, Stream stream)
{
object underlyingValue = Convert.ChangeType(value, _underlyingMarshaler.ManagedType);
_underlyingMarshaler.MarshalObject(underlyingValue, stream);
}
19
View Source File : SqlMapper.Async.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
internal static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, Type effectiveType, CommandDefinition command)
{
object param = command.Parameters;
var idenreplacedy = new Idenreplacedy(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType(), null);
var info = GetCacheInfo(idenreplacedy, param, command.AddToCache);
bool wasClosed = cnn.State == ConnectionState.Closed;
var cancel = command.CancellationToken;
using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader))
{
DbDataReader reader = null;
try
{
if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false);
reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, cancel).ConfigureAwait(false);
var tuple = info.Deserializer;
int hash = GetColumnHash(reader);
if (tuple.Func == null || tuple.Hash != hash)
{
if (reader.FieldCount == 0)
return Enumerable.Empty<T>();
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));
if (command.AddToCache) SetQueryCache(idenreplacedy, info);
}
var func = tuple.Func;
if (command.Buffered)
{
var buffer = new List<T>();
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
while (await reader.ReadAsync(cancel).ConfigureAwait(false))
{
object val = func(reader);
if (val == null || val is T)
{
buffer.Add((T)val);
}
else
{
buffer.Add((T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture));
}
}
while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore subsequent result sets */ }
command.OnCompleted();
return buffer;
}
else
{
// can't use ReadAsync / cancellation; but this will have to do
wasClosed = false; // don't close if handing back an open reader; rely on the command-behavior
var deferred = ExecuteReaderSync<T>(reader, func, command.Parameters);
reader = null; // to prevent it being disposed before the caller gets to see it
return deferred;
}
}
finally
{
using (reader) { /* dispose if non-null */ }
if (wasClosed) cnn.Close();
}
}
}
19
View Source File : SqlMapper.Async.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
internal static async Task<T> QueryRowAsync<T>(this IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command)
{
object param = command.Parameters;
var idenreplacedy = new Idenreplacedy(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType(), null);
var info = GetCacheInfo(idenreplacedy, param, command.AddToCache);
bool wasClosed = cnn.State == ConnectionState.Closed;
var cancel = command.CancellationToken;
using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader))
{
DbDataReader reader = null;
try
{
if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false);
reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, (row & Row.Single) != 0
? CommandBehavior.SequentialAccess | CommandBehavior.SingleResult // need to allow multiple rows, to check fail condition
: CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow, cancel).ConfigureAwait(false);
T result = default(T);
if (await reader.ReadAsync(cancel).ConfigureAwait(false) && reader.FieldCount != 0)
{
var tuple = info.Deserializer;
int hash = GetColumnHash(reader);
if (tuple.Func == null || tuple.Hash != hash)
{
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));
if (command.AddToCache) SetQueryCache(idenreplacedy, info);
}
var func = tuple.Func;
object val = func(reader);
if (val == null || val is T)
{
result = (T)val;
}
else
{
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
result = (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
}
if ((row & Row.Single) != 0 && await reader.ReadAsync(cancel).ConfigureAwait(false)) ThrowMultipleRows(row);
while (await reader.ReadAsync(cancel).ConfigureAwait(false)) { /* ignore rows after the first */ }
}
else if ((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one
{
ThrowZeroRows(row);
}
while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore result sets after the first */ }
return result;
}
finally
{
using (reader) { /* dispose if non-null */ }
if (wasClosed) cnn.Close();
}
}
}
19
View Source File : SqlMapper.GridReader.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
private T ReadRow<T>(Type type, Row row)
{
if (reader == null) throw new ObjectDisposedException(GetType().FullName, "The reader has been disposed; this can happen after all data has been consumed");
if (IsConsumed) throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once");
IsConsumed = true;
T result = default(T);
if (reader.Read() && reader.FieldCount != 0)
{
var typedIdenreplacedy = idenreplacedy.ForGrid(type, gridIndex);
CacheInfo cache = GetCacheInfo(typedIdenreplacedy, null, addToCache);
var deserializer = cache.Deserializer;
int hash = GetColumnHash(reader);
if (deserializer.Func == null || deserializer.Hash != hash)
{
deserializer = new DeserializerState(hash, GetDeserializer(type, reader, 0, -1, false));
cache.Deserializer = deserializer;
}
object val = deserializer.Func(reader);
if (val == null || val is T)
{
result = (T)val;
}
else
{
var convertToType = Nullable.GetUnderlyingType(type) ?? type;
result = (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
}
if ((row & Row.Single) != 0 && reader.Read()) ThrowMultipleRows(row);
while (reader.Read()) { /* ignore subsequent rows */ }
}
else if ((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one
{
ThrowZeroRows(row);
}
NextResult();
return result;
}
19
View Source File : SqlMapper.GridReader.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
private IEnumerable<T> ReadDeferred<T>(int index, Func<IDataReader, object> deserializer, Type effectiveType)
{
try
{
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
while (index == gridIndex && reader.Read())
{
object val = deserializer(reader);
if (val == null || val is T)
{
yield return (T)val;
}
else
{
yield return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
}
}
}
finally // finally so that First etc progresses things even when multiple rows
{
if (index == gridIndex)
{
NextResult();
}
}
}
19
View Source File : SqlMapper.IDataReader.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
public static IEnumerable<T> Parse<T>(this IDataReader reader)
{
if (reader.Read())
{
var effectiveType = typeof(T);
var deser = GetDeserializer(effectiveType, reader, 0, -1, false);
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
do
{
object val = deser(reader);
if (val == null || val is T)
{
yield return (T)val;
}
else
{
yield return (T)Convert.ChangeType(val, convertToType, System.Globalization.CultureInfo.InvariantCulture);
}
} while (reader.Read());
}
}
19
View Source File : JsonConfigUtils.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public T GetAppConfig<T>(string key, T defaultValue = default(T))
{
T value = default(T);
try
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", true, false)
.AddJsonFile($"appsettings.{env}.json", true, false)
.AddEnvironmentVariables();
var configuration = builder.Build();
value = (T)Convert.ChangeType(configuration[key], typeof(T));
if (value == null)
value = defaultValue;
}
catch (Exception)
{
value = defaultValue;
}
return value;
}
19
View Source File : HttpHelper.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static T GetApi<T>(string baseUrl, string url, string pragm = "")
{
var client = new RestSharpClient(baseUrl);
var request = client.Execute(string.IsNullOrEmpty(pragm)
? new RestRequest(url, Method.GET)
: new RestRequest($"{url}?{pragm}", Method.GET));
if (request.StatusCode != HttpStatusCode.OK)
{
return (T)Convert.ChangeType(request.ErrorMessage, typeof(T));
}
dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(request.Content, typeof(T));
//T result = (T)Convert.ChangeType(request.Content, typeof(T));
return (T)temp;
}
19
View Source File : HttpHelper.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static T PostApi<T>(string url, object body = null)
{
var client = new RestClient($"{url}");
IRestRequest queest = new RestRequest();
queest.Method = Method.POST;
queest.AddHeader("Accept", "application/json");
queest.AddJsonBody(body); // 可以使用 JsonSerializer
var result = client.Execute(queest);
if (result.StatusCode != HttpStatusCode.OK)
{
return (T)Convert.ChangeType(result.ErrorMessage, typeof(T));
}
dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Content, typeof(T));
//T result = (T)Convert.ChangeType(request.Content, typeof(T));
return (T)temp;
}
19
View Source File : Engine.cs
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
static System.Linq.Expressions.Expression BuildExpr<T>(Expression r, ParameterExpression param)
{
var left = MemberExpression.Property(param, r.MemberName);
var tProp = typeof(T).GetProperty(r.MemberName).PropertyType;
ExpressionType tBinary;
// is the operator a known .NET operator?
if (ExpressionType.TryParse(r.Operator, out tBinary))
{
var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tProp));
// use a binary operation, e.g. 'Equal' -> 'u.Age == 15'
return System.Linq.Expressions.Expression.MakeBinary(tBinary, left, right);
}
if (r.Operator == "MatchRegex" || r.Operator == "NotMatchRegex")
{
var regex = new Regex(r.TargetValue);
var method = typeof(Regex).GetMethod("IsMatch", new[] {typeof(string)});
Debug.replacedert(method != null, nameof(method) + " != null");
var callInstance = System.Linq.Expressions.Expression.Constant(regex);
var toStringMethod = tProp.GetMethod("ToString", new Type[0]);
Debug.replacedert(toStringMethod != null, nameof(toStringMethod) + " != null");
var methodParam = System.Linq.Expressions.Expression.Call(left, toStringMethod);
var call = System.Linq.Expressions.Expression.Call(callInstance, method, methodParam);
if (r.Operator == "MatchRegex") return call;
if (r.Operator == "NotMatchRegex") return System.Linq.Expressions.Expression.Not(call);
}
if (tProp.Name == "String")
{
var method = tProp.GetMethod(r.Operator, new Type[] { typeof(string) });
var tParam = method.GetParameters()[0].ParameterType;
var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
// use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
return System.Linq.Expressions.Expression.Call(left, method, right);
}
else {
var method = tProp.GetMethod(r.Operator);
var tParam = method.GetParameters()[0].ParameterType;
var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
// use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
return System.Linq.Expressions.Expression.Call(left, method, right);
}
}
19
View Source File : ValueMember.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
private static object ParseDefaultValue(Type type, object value)
{
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
}
if (value is string s)
{
if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean: return bool.Parse(s);
case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
if (s.Length == 1) return s[0];
throw new FormatException("Single character expected: \"" + s + "\"");
case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.String: return s;
case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
case ProtoTypeCode.Uri: return s; // Uri is decorated as string
case ProtoTypeCode.Guid: return new Guid(s);
}
}
if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
19
View Source File : TimelineModel.DefaultValues.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
private void SetDefaultValues()
{
var defaults = this.Defaults.Union(GetSuperDefaultValues())
.Where(x => (x.Enabled ?? true));
this.Walk((element) =>
{
inheritsElement(element);
setDefaultValuesToElement(element);
return false;
});
void setDefaultValuesToElement(TimelineBase element)
{
try
{
foreach (var def in defaults
.Where(x => x.TargetElement == element.TimelineType))
{
var pi = GetPropertyInfo(element, def.TargetAttribute);
if (pi == null)
{
continue;
}
var value = pi.GetValue(element);
if (value == null)
{
object defValue = null;
if (def.Value != null)
{
var type = pi.PropertyType;
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
type = Nullable.GetUnderlyingType(type);
}
if (!type.IsEnum)
{
defValue = Convert.ChangeType(def.Value, type);
}
else
{
defValue = Enum.Parse(type, def.Value, true);
}
}
if (defValue != null)
{
pi.SetValue(element, defValue);
}
}
}
}
catch (Exception ex)
{
Logger.Write($"{TimelineConstants.LogSymbol} Load default values error.", ex);
}
}
void inheritsElement(TimelineBase element)
{
if (string.IsNullOrEmpty(element.Inherits))
{
return;
}
var super = default(TimelineBase);
this.Walk(x =>
{
if (x.Enabled.GetValueOrDefault() &&
x.TimelineType == element.TimelineType &&
!string.IsNullOrEmpty(x.Name) &&
string.Equals(x.Name, element.Inherits, StringComparison.OrdinalIgnoreCase))
{
super = x;
return true;
}
return false;
});
if (super == null)
{
return;
}
var properties = super.GetType().GetProperties(
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic);
foreach (var pi in properties)
{
var superValue = pi.GetValue(super);
if (superValue == null)
{
continue;
}
var targetValue = pi.GetValue(element);
if (targetValue == null)
{
pi.SetValue(element, superValue);
}
}
}
}
19
View Source File : CybtansModelBinder.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
private static void SetValue(ModelBindingContext bindingContext, object obj, string value, string property)
{
if (obj is IReflectorMetadataProvider reflectorMetadata)
{
var accesor = reflectorMetadata.GetAccesor();
var propCode = accesor.GetPropertyCode(Pascal(property));
var propType = accesor.GetPropertyType(propCode);
propType = Nullable.GetUnderlyingType(propType) ?? propType;
reflectorMetadata.SetValue(Pascal(property),
propType != typeof(string) ?
Convert.ChangeType(value, propType) :
value);
}
else
{
var prop = bindingContext.ModelMetadata.Properties.FirstOrDefault(x => x.Name.ToUpperInvariant() == property.ToUpperInvariant());
prop?.PropertySetter(obj,
prop.ModelType != typeof(string) ?
Convert.ChangeType(value, prop.UnderlyingOrModelType) :
value);
}
}
19
View Source File : URISupport.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static void SetProperties(object target, StringDictionary map)
{
Type type = target.GetType();
foreach (string key in map.Keys)
{
PropertyInfo prop = type.GetProperty(key,
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.IgnoreCase);
if (null != prop)
{
prop.SetValue(target, Convert.ChangeType(map[key], prop.PropertyType, CultureInfo.InvariantCulture),
null);
}
else
{
FieldInfo field = type.GetField(key,
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.IgnoreCase);
if (null != field)
{
field.SetValue(target,
Convert.ChangeType(map[key], field.FieldType, CultureInfo.InvariantCulture));
}
else
{
throw new NMSException(string.Format("No such property or field: {0} on clreplaced: {1}", key,
target.GetType().Name));
}
}
}
}
See More Examples