c# - 根据属性值在 C# 中查找函数

标签 c# linq reflection

我想通过一些适配器基于属性值访问类的函数。所有函数都有相同的原型(prototype)
我想这样做的方式是像这样声明一个字典:

Dictionary<key_values, Delegate_of_Functions>

其中 key_values 是一个包含标识函数的值的类,而 Delegate_of_Functions 是函数类型的委托(delegate)。

现在,我尝试执行以下操作:

Functions = new Dictionary<string, function>();

var a = from Fun in typeof(TheFunctionsContainer).GetMethods()
        where Fun.GetCustomAttributes(typeof(The_Attribute), true).Length != 0
        select Fun;

foreach (var c in a)
{
  Functions.Add(
    c.GetCustomAttributes(true).OfType<The_Attribute>().First().key,
    new function(c)); // this line dose not compile
}

我的问题是:

  • 如何让未编译的行编译?
  • 有更好的方法吗?

最佳答案

鉴于 function 是一个委托(delegate)

delegate void function();

您可以使用 Delegate.CreateDelegate创建委托(delegate)的方法

var Functions = new Dictionary<string, function>();

var a = typeof(TheFunctionsContainer).GetMethods().Where(f => f.GetCustomAttributes(typeof(The_Attribute), true).Any());

foreach (var c in a)
{
    Functions.Add(
      c.GetCustomAttributes(true).OfType<The_Attribute>().First().key,
      (function)Delegate.CreateDelegate(typeof(function), c)); 
}

如果你想在一个实例上执行非静态方法,你必须提供你想要方法调用的实例Delegate.CreateDelegate :

(function)Delegate.CreateDelegate(typeof(function), yourInstance, c)

或者只看 svicks 评论 :-)

关于c# - 根据属性值在 C# 中查找函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12159459/

相关文章:

c# - 如何用twain/emgu/open cv达到好的清晰度?

c# - LINQ DataRowExtensions.Field<int> 必须是 <decimal>?

linq - 如何将此逻辑转换为 LINQ 语句?

c# - 分组和计数

java - 小程序和 Jackson 外部 jar : Can not access public class

c# - 如何在 C#/Vista 中将鼠标事件传递给我背后的应用程序?

c# - 最小化 FormClose 防止计算机关机

c# - 如何从 Action() 返回值?

c# - 将依赖项注入(inject)动态加载的 .dll (.net core)

objective-c - 在 Obj-C 中发现给定类的子类