: , , .
, , "op_Implicit" .
So, I created this (rather long) and hacky helper method that converts a type TObjectobject to a type object TTo, taking into account the implicit conversion operators:
public static object Convert<TObject, TTo>(TObject obj)
{
IEnumerable<MethodInfo> implicitConversionOperators = obj.GetType()
.GetMethods()
.Where(mi => mi.Name == "op_Implicit");
MethodInfo fittingImplicitConversionOperator = null;
foreach (MethodInfo methodInfo in implicitConversionOperators)
{
if (methodInfo.GetParameters().Any(parameter => parameter.ParameterType == typeof(TObject)))
{
fittingImplicitConversionOperator = methodInfo;
}
}
if (fittingImplicitConversionOperator != null)
{
return fittingImplicitConversionOperator.Invoke(null, new object[] {obj});
}
return (TTo) System.Convert.ChangeType(obj, typeof(TTo));
}
Of course, it is far from perfect, but it can be used like this.
propertyInfo.SetValue(this, Helper.Convert<TcBool, bool>(new TcBool(true)));
to set the property. Of course, if you do not know the types at compile time / do not want this to be detailed information, you can try dynamic, etc., as shown in other answers.
source
share