Suppose you have a class Foo:
public class Foo
{
public static implicit operator Foo(string s)
{
return new Foo();
}
}
If you try to leverage this operator in the usual way it works fine, of course:
var s = "foo";
Foo foo = s;
But what if you have the operand (s) but you only have it as an object:
object s = "foo";
Foo foo = s;
This fails for obvious reasons since there is no implicit conversion from object to Foo. However, the instance is a string and a type conversion operator does exist for this scenario. For the purpose of this question, assume that the variable in question (s) could be any of a number of types that might possibly have a type conversion operator defined to perform the requested conversion.
If you wanted, you could use reflection:
object s = "foo";
var converter = typeof(Foo)
.GetMethods()
.Single(x =>
x.Name == "op_Implicit" &&
x.ReturnType == typeof(Foo) &&
x.GetParameters().Single().ParameterType == typeof(string));
Foo foo = (Foo)converter.Invoke(null, new[] { s });
I tried using Convert.ChangeType(s, typeof(Foo));, but this does not work. Is there any better alternative or is using reflection the best choice? (I'm unhappy with using reflection for the standard reasons -- it's probably not maximally performant and the appearance of the code is unseemly. But if it's the best bet, then fine.)
Aucun commentaire:
Enregistrer un commentaire