Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# typeof()参数-它是如何工作的?_C#_.net - Fatal编程技术网

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

C# typeof()参数-它是如何工作的?,c#,.net,C#,.net,在下面的代码中: string GetName(Type type) { return ((type)this.obj).Name; } void Run() { string name = GetName(typeof(MyClass)); } 我收到一个“找不到类型或名称空间(是否缺少使用指令或程序集引用?”错误。我该怎么做才能更正此问题?您不能强制转换到实例 type是type类的实例,如果要强制转换为

在下面的代码中:

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

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

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

您不能强制转换到实例

type是type类的实例,如果要强制转换为特定类型,请使用泛型

void GetName<T>() where T : IObjectWithName { return ((T)this.object).Name; }
void GetName(),其中T:IObjectWithName{return((T)this.object).Name;}
然后你可以打电话

string name = GetName<MyClass>();
string name=GetName();

如果这是合理的。

您不能对实例进行强制转换

type是type类的实例,如果要强制转换为特定类型,请使用泛型

void GetName<T>() where T : IObjectWithName { return ((T)this.object).Name; }
void GetName(),其中T:IObjectWithName{return((T)this.object).Name;}
然后你可以打电话

string name = GetName<MyClass>();
string name=GetName();

如果这样做是有道理的。

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

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

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

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

在正确名称空间的顶部是否有正确的用法?
(type)(this.object).Name
看起来完全错误-
Update
方法尝试做什么?它的“((type)this.obj).Name”,对不起。您是否在顶部使用了正确的名称空间?
(type)(this.object).Name
看起来完全错了,
Update
方法试图做什么?它的“((type)this.obj.Name)”很抱歉。它引入了一个额外的接口,如果有许多不同的类具有Name属性,OP可能不需要这个接口。@Lemuel Adane:那么他们只需要实现IObjectWithName。如果你解释清楚你到底想做什么,也许我们可以帮你进一步。我现在明白你的意思了。非常感谢。它引入了一个额外的接口,如果有许多不同的类具有Name属性,OP可能不需要这个接口。@Lemuel Adane:那么他们只需要实现IObjectWithName。如果你解释清楚你到底想做什么,也许我们可以帮你进一步。我现在明白你的意思了。谢谢。