使用反射转换为通用类型对象

发布于 2024-12-20 14:34:38 字数 92 浏览 1 评论 0原文

如果我直到运行时才知道 T 是什么,我可以使用反射将对象从 object 类型转换为 MyType 吗?

Can I cast an object from type object to MyType<T> using reflection if I don't know what T is until runtime?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一身软味 2024-12-27 14:34:38

在这种情况下,技巧是使用具有泛型方法的非泛型类。

public class MyType
{
    public T GetResult<T>() {
    }
}

但请注意,这发生在编译时。泛型让您有机会在编译时创建不同“风格”的类型或方法;但泛型不是动态的!泛型是类型安全的,类型安全只能在编译时实现(因为是编译器检查类型安全)。

The trick in such situations, is to use a non-generic class with generic methods.

public class MyType
{
    public T GetResult<T>() {
    }
}

Note, however, that this happens at compile time. Generics give you the opportunity to create different "flavors" of a type or a method at compile time; but generics are not dynamic! Generics are type-safe and type safety can only be achieved at compile time (because it's the compiler who checks the type safety).

梦途 2024-12-27 14:34:38

您无法在编译时强制转换为未知类型。强制转换实际上仅作为编译时构造有用,因为您需要知道类型才能直接使用它。

但是,如果您的目标是通过反射处理对象,那就是不同的情况了。在这种情况下,您可以使用 Type.MakeGenericType 创建正确的类型你的对象。

这将允许您使用反射来处理您的对象。

You can't cast to a type unknown at compile time. Casting is really only useful as a compile-time construct, as you'd need to know the type in order to use it directly.

If your goal is to work with the object via Reflection, however, that's a different scenario. In that case, you can use Type.MakeGenericType to create the correct type for your object.

This will allow you to use reflection to work upon your object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文