c#中是否可以通过字符串访问类
本文关键字:访问 字符串 可以通过 是否 | 更新日期: 2023-09-27 18:17:25
我运行了一个sql存储过程,它返回一个类名。例如,它返回"orange"。我有一门课叫"橙色"。是否可以使用返回字符串访问orange.GrabFiles?
谢谢!
您可以使用System。反射来获得你需要的类并调用你想调用的方法。
要做到这一点,您可以遍历程序集的所有类型并选择适合您的类型。如果您有特殊的名称,您可以使用属性将特定类型与特殊名称链接起来。
搜索类型
// 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, ...);
假设"orange"的名称空间为"fruits",则可以执行以下操作:
dynamic d = Activator.CreateInstance(Type.GetType("fruits.orange"));
d.GrabFiles();
非常简单和直接,只要你知道你的代码在做什么。
如果只有几个返回值,并且在编译时都是已知的,那么检查结果并相应地进行分支(使用switch
或if
s序列)会更简单。
如果你需要更多的动态行为,你可以使用Type typeToCall = Type.GetType(typeName);
,然后使用typeToCall.InvokeMember(...)
。