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);
}
精彩评论