任何人都可以解释如何得到这个工作?我传递的类型名称,而T被正确填充。我只是想不通怎么投objectToCast以T型。任何帮助是AP preciated。
Can anyone explain how to get this to work? I am passing in the type name, and "t" is being correctly populated. I just cannot figure out how to cast objectToCast to type "t". Any help is appreciated.
....
Type t = Type.GetType("castToTypeNameHere");
o = CastTo<t>(objectToCast);
....
private T CastTo<T>(Object obj)
{
return (T)obj;
}
仅供参考,这里我找到了答案:
FYI, here's the answer I found:
Type t = Type.GetType(element.Attribute("castToType").Value);
MethodInfo castMethod = this.GetType().GetMethod("CastTo", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(t);
object castedObject = castMethod.Invoke(this, new object[] { objectToCast });
推荐答案
在使用泛型(无反射),类型参数必须是类型的名称,而不是实例的System.Type
。所以你不能说
When you use generics (without reflection), the type parameters have to be the name of types, not instances of System.Type
. So you can't say
由于 T
不是一个类型的名称。这是因为如果你说的
Type t = Type.GetType("castToTypeNameHere");
o = CastTo<t>(objectToCast);
because t
is not the name of a type. It's as if you had said
而不是
o = CastTo<int>(objectToCast);
,前者是非法的,后者是合法的。
The former is illegal, the latter is legal.
我不明白你要达到什么目的。如果你不知道在编译时的类型,一个演员一样,是没有用的。编译器将不知道 0
的类型,你不会得到任何的编译时类型安全,也没有智能感知功能。
I don't understand what you're trying to achieve. If you don't know the type at compile time, a cast like that is useless. The compiler won't know the type of o
, and you won't get any of the compile-time type safety nor IntelliSense features.
相关推荐
最新文章