我实现了从字符串到名为 Foo 的对象的显式转换。
So => Foo f = (Foo)"foo 数据";有效
我需要实现一个将字符串转换为泛型 T 的函数,在这种情况下,T 是 Foo 数据类型。
public T Get<T>(object o){
// this always return false
if (typeof(T).IsAssignableFrom(typeof(String)))
{
// when i by pass the if above this throws invalid cast exception
return (T)(object)str;
}
return null;
}
// When I call this, it generated an error
// Invalid cast from 'System.String' to Foo
Foo myObj = Get<Foo>("another foo object");
// when I use the dynamic keyword it works but this is C# 4.0+ feature, my function is in the older framework
return (T)(dynamic)str;
最佳答案
一个使用反射的例子:
class Program
{
static void Main(string[] args)
{
Foo myObj = TypeResolver.Get<Foo>("Foo data");
}
}
class TypeResolver
{
public static T Get<T>(object obj)
{
if (typeof(T).CanExplicitlyCastFrom<string>())
{
return obj.CastTo<T>();
}
return default(T);
}
}
public static class Extensions
{
public static bool CanExplicitlyCastFrom<T>(this Type type)
{
if (type == null)
throw new ArgumentNullException("type");
var paramType = typeof(T);
var castOperator = type.GetMethod("op_Explicit",
new[] { paramType });
if (castOperator == null)
return false;
var parametres = castOperator.GetParameters();
var paramtype = parametres[0];
if (paramtype.ParameterType == typeof(T))
return true;
else
return false;
}
public static T CastTo<T>(this object obj)
{
var castOperator = typeof(T).GetMethod("op_Explicit",
new[] { typeof(string) });
if (castOperator == null)
throw new InvalidCastException("Can't cast to " + typeof(T).Name);
return (T)castOperator.Invoke(null, new[] { obj });
}
}
关于c# - 泛型显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16114226/