C# 如何将字符串转换为类引用
我有字符串类名,我想将其转换为类引用C# 如何将字符串转换为类引用,c#,C#,我有字符串类名,我想将其转换为类引用 if (System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()] != null) { (System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()] as PC_01).accept(); } 我想用
if (System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()] != null)
{
(System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()] as PC_01).accept();
}
我想用string
“PC_01”
代替classPC_01
尝试使用Activator
class。请参见如果要将对象的类型表示为字符串,可以在type类的帮助下执行,并使用dynamic调用此实例的方法
object obj = System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()];
Type t = Type.GetType("myNamespace.PC_01, myAssembly");
if (obj.GetType() == t)
{
((dynamic)obj).accept();
}
.Ivan,对于未来:在答案中发布一个小代码示例,而不仅仅是一个链接,这是一个很好的实践。