开发者

typeof() parameter - how does it work?

In the Code below:

string GetName(Type type)    
{       
    return ((type)thi开发者_高级运维s.obj).Name;    
}    

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

Im getting a "The type or name space cannot be found (are you missing using a directive or assembly reference?)" error. What should I do to correct this?


You can't cast to an instance !

type is a instance of the Type class, if you want to cast to certain Type, use Generics

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

then you can call

string name = GetName<MyClass>();

If that makes sens.


You can't do like this, you need Reflection to do something like what you are asking for:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜