I realize the title needs to be read more than once for understanding ... :)
I implemented a custom attribute that i apply to methods in my classes. all methods i apply the attribute to have the same signature and thus i defined a delegate for them:
public delegate void TestMethod();
I have a struct that accepts that delegate as a parameter
struct TestMetaData
{
TestMethod method;
string testName;
}
Is it possible to get from reflection a method that has the custom attribute and pass it to the struct into the 'method' member ?
I know you can invoke it but i think reflection won't give me the actual method from my class that i can cast to the TestMethod delegate.
通过Reflection获得MethodInfo后,可以使用Delegate.CreateDelegate将其转换为Delegate,然后使用Reflection将其直接设置为结构的属性/字段。
You can create a delegate that calls your reflected method at runtime using Invoke, or Delegate.CreateDelegate.
Example:
using System;
class Program
{
public delegate void TestMethod();
public class Test
{
public void MyMethod()
{
Console.WriteLine("Test");
}
}
static void Main(string[] args)
{
Test t = new Test();
Type test = t.GetType();
var reflectedMethod = test.GetMethod("MyMethod");
TestMethod method = (TestMethod)Delegate.CreateDelegate(typeof(TestMethod), t, reflectedMethod);
method();
}
}
您还需要已声明合适的委托
As an example:
using System;
using System.Linq;
using System.Reflection;
public delegate void TestMethod();
class FooAttribute : Attribute { }
static class Program
{
static void Main() {
// find by attribute
MethodInfo method =
(from m in typeof(Program).GetMethods()
where Attribute.IsDefined(m, typeof(FooAttribute))
select m).First();
TestMethod del = (TestMethod)Delegate.CreateDelegate(
typeof(TestMethod), method);
TestMetaData tmd = new TestMetaData(del, method.Name);
tmd.Bar();
}
[Foo]
public static void TestImpl() {
Console.WriteLine("hi");
}
}
struct TestMetaData
{
public TestMetaData(TestMethod method, string name)
{
this.method = method;
this.testName = name;
}
readonly TestMethod method;
readonly string testName;
public void Bar() { method(); }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.