我运行了一个返回类名的 sql 存储过程。例如,它返回“橙色”。我有一个名为“橙色”的类(class)。是否可以使用该返回字符串访问 orange.GrabFiles?
谢谢!
最佳答案
您可以使用 System.Reflection 获取您需要的类并调用您要调用的方法。
为此,您可以遍历所有类型的程序集并为您选择正确的一种。如果您有特殊名称,您可以使用属性将特定类型与特殊名称联系起来。
搜索类型
// Type to find
String name = "orange";
// I assume you only use one assembly
Assembly asm = Assembly.GetCallingAssembly();
// Iterate though all types
foreach (Type item in asm.GetTypes())
{
if (item.Name == name)
{
return item;
}
else
{
// A class can have multiple SpecialNameAttributes, this is a attribute you have to create
SpecialNameAttribute[] attributes = (SpecialNameAttribute[])item.GetCustomAttributes(typeof(SpecialNameAttribute));
foreach (SpecialNameAttribute attribute in attributes)
{
if (attribute.Name == name) return item;
}
}
}
return null;
调用方法
创建实例:
Object instance = Activator.CreateInstance(typeFound);
typeFound.GetMethod("GrabFiles").Invoke(instance, ...);
没有实例:
typeFound.GetMethod("GrabFiles").Invoke(null, ...);
关于c# - 在 C# 中可以通过字符串访问类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8464539/