【发布时间】:2013-04-19 22:10:15
【问题描述】:
我实现了从字符串到名为 Foo 的对象的显式转换。
So => Foo f = (Foo)"foo data";有效
我需要实现一个将字符串转换为通用 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;
【问题讨论】:
-
你应该改用
TypeConverters。 -
Foo的定义是什么?是否有implicit(msdn.microsoft.com/en-us/library/z5z9kes2%28v=vs.71%29.aspx) 或explicit(msdn.microsoft.com/en-us/library/xhbhezf4%28v=vs.71%29.aspx) 运算符重载? -
@CodingWithSpike Foo 有显式转换 Foo itm = (Foo)"string"
-
看起来编译器不知道
T会有用户提供的explicit运算符,所以简单地转换(T)str不会编译。如果您将泛型限制为Foo,那么它可以构建并正常工作,但这违背了泛型的目的,因为您只能指定Foo。寻找一种方法来诱使编译器允许这样做... -
@AaronLS 不会编译。