如何将类型转换为类型名称? [英] How do I cast a type to a typename?

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

问题描述

假设我有一个带有通用参数的方法,我该如何输入:

Say I have a method with generic parameters, how do I enter:

doSomething<foo.GetType()>();





为什么这不起作用?如何使这项工作?



Why doesn't this work and how can I make this work?

推荐答案

As我知道, foo.GetType()是在运行时调用的,所以你应该尝试使用 typeof(foo)在编译时管理。
As I know, foo.GetType() is invoked at runtime, so you should try by using typeof(foo) that is managed at compile time.


为什么?简单:因为你没有参数,所以在编译时决定调用你的方法的类型 - 不能从用法中推断出类型。这意味着你必须提供一个常量类型说明符,而不是方法调用。



相反,试试这个:

Why? Simple: because you have no parameters, the decision as to what type to call your method with is decided at compile time - the type cannot be inferred from the usage. Which mean you have to provide a constant type specifier, rather than a method call.

Instead, try this:
private void DoSomething<T>()
    {
    Console.WriteLine("DoSomething:" + typeof(T));
    }
private void DoSomething<T>(T x)
    {
    Console.WriteLine("DoSomething:" + x.GetType());
    }

然后你可以调用它:

Then you can call it:

DoSomething<int>();
DoSomething<float>();
double d = 12.34;
DoSomething(d);

得到你想要的东西:

And get what you want:

DoSomething:System.Int32
DoSomething:System.Single
DoSomething:System.Double


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

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