typeof()参数 - 它是如何工作的?

时间:2010-12-21 11:11:27

标签: c# .net

在下面的代码中:

string GetName(Type type)    
{       
    return ((type)this.obj).Name;    
}    

void Run()    
{       
    string name = GetName(typeof(MyClass));    
}

我得到了“找不到类型或名称空间(你是否缺少使用指令或程序集引用?)”错误。我该怎么做才能纠正这个问题?

2 个答案:

答案 0 :(得分:7)

您无法转换为实例!

type是Type类的一个实例,如果要转换为某个Type,请使用Generics

void GetName<T>() where T : IObjectWithName { return ((T)this.object).Name; }

然后你可以打电话

string name = GetName<MyClass>();

如果那样有感觉。

答案 1 :(得分:1)

你不能这样做,你需要反思来做你想要的事情:

void Update(Type type)
{
    PropertyInfo info = type.GetProperty("Name");
    string name = info.GetValue(info, null);
}