c# - 在 C# 中可以通过字符串访问类吗?

标签 c#

我运行了一个返回类名的 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/

相关文章:

c# - 在 C# 中使用表达式创建通用委托(delegate)

c# - c#中存储过程中的await关键字放在哪里

c# - LINQ 执行查询

c# - 尝试从 Cosmos DB 中删除时找不到资源

c# - 领域驱动设计适合我的项目吗?

c# - 为什么 Trackbar 值在向上箭头/PgUp 上减少?

c# - 以编程方式从 Microsoft Word 功能区中删除组

c# - 请求 channel 在等待回复时超时

c# - 具有动态列的 LINQ Pivot

c# - 如何从 EnvDTE.Window 中获取 ITextBuffer?