开发者

typeof() parameter - how does it work?

开发者 https://www.devze.com 2023-01-31 09:27 出处:网络
In the Code below: string GetName(Type type) { return ((type)thi开发者_高级运维s.obj).Name; } void Run()

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

精彩评论

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