Created
October 10, 2012 05:20
-
-
Save nakamura-to/3863309 to your computer and use it in GitHub Desktop.
TryChangeType with op_Explicit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var value = new Celsius(10); | |
Fahrenheit result; | |
if (TryChangeType(value, typeof(Fahrenheit), out result)) | |
{ | |
Console.WriteLine(result.Degrees); // 50 | |
} | |
Console.ReadKey(); | |
} | |
private static bool TryChangeType<T>(object value, Type destType, out T destValue) | |
{ | |
if (value == null) | |
{ | |
destValue = default(T); | |
return false; | |
} | |
var srcType = value.GetType(); | |
var method = srcType.GetMethods(BindingFlags.Static | BindingFlags.Public) | |
.Where(m => m.Name == "op_Explicit") | |
.Where(m => | |
{ | |
var parameters = m.GetParameters(); | |
return parameters.Length == 1 && parameters[0].ParameterType == srcType; | |
}).FirstOrDefault(m => destType.IsAssignableFrom(m.ReturnType)); | |
if (method == null) | |
{ | |
destValue = default(T); | |
return false; | |
} | |
destValue = (T)method.Invoke(value, new[] { value }); | |
return true; | |
} | |
} | |
class Celsius | |
{ | |
public Celsius(float temp) | |
{ | |
degrees = temp; | |
} | |
public static explicit operator Fahrenheit(Celsius c) | |
{ | |
return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32); | |
} | |
public float Degrees | |
{ | |
get { return degrees; } | |
} | |
private float degrees; | |
} | |
class Fahrenheit | |
{ | |
public Fahrenheit(float temp) | |
{ | |
degrees = temp; | |
} | |
public static explicit operator Celsius(Fahrenheit f) | |
{ | |
return new Celsius((5.0f / 9.0f) * (f.degrees - 32)); | |
} | |
public float Degrees | |
{ | |
get { return degrees; } | |
} | |
private float degrees; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment