我想从调用方法中获取一个 MethodInfo 对象,以确定该方法是否设置了特殊属性。
具有调用方法 Run() 的 Programm 类
class Program
{
private static RestHandler _handler = new RestHandler();
static void Main(string[] args)
{
Run();
}
[Rest("GET")]
static void Run()
{
_handler.Handler(typeof(Program));
}
}
Run Code Online (Sandbox Code Playgroud)
我想确定自定义属性的类
public class RestHandler
{
public void Handler(Type t)
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
var attributes = methodInfo.GetCustomAttributes<RestAttribute>();
}
}
Run Code Online (Sandbox Code Playgroud)
属性类
public class RestAttribute : Attribute
{
public RestAttribute(string method)
{
Method = …
Run Code Online (Sandbox Code Playgroud) 我想获得被委派为Func的方法的名称.
Func<MyObject, object> func = x => x.DoSomeMethod();
string name = ExtractMethodName(func); // should equal "DoSomeMethod"
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
- 吹牛的权利 -
Make ExtractMethodName
也可以使用属性调用,让它返回该实例中的属性名称.
例如.
Func<MyObject, object> func = x => x.Property;
string name = ExtractMethodName(func); // should equal "Property"
Run Code Online (Sandbox Code Playgroud) 我怎么打电话SomeObject.SomeGenericInstanceMethod<T>(T arg)
?
有一些关于调用泛型方法的帖子,但不完全像这个.问题是method参数被约束为泛型参数.
我知道如果签名是相反的
SomeObject.SomeGenericInstanceMethod<T>(string arg)
然后我可以得到MethodInfo
typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[]{typeof (string)}).MakeGenericMethod(typeof(GenericParameter))
那么,当常规参数是泛型类型时,如何获取MethodInfo?谢谢!
此外,泛型参数可能有也可能没有类型约束.
我刚刚阅读了这个MethodInfo
类型并遇到了这种类型,并认为它起初是某种类型的非托管类.然后看到它实际上是一个界面.
谁知道为什么没有命名IMethodInfo
?我认为前缀接口I
是.NET中的标准做法.是因为一些命名冲突?