如何转换为在C#中的类型 [英] How to cast to a type in C#

查看:127
本文介绍了如何转换为在C#中的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释如何得到这个工作?我传递的类型名称,而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.

这篇关于如何转换为在C#中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆