有没有办法确定参数是否具有此修饰符?

Sel*_*enç 4 c# reflection extension-methods

我想确定一个参数是否有this修饰符使用Reflection.我已经查看了ParameterInfo类的属性,但找不到任何有用的东西.我知道扩展方法只是语法糖但我相信应该有一种方法来确定一个方法是一种扩展方法.

从其他静态方法(在中定义的区别扩展方法唯一的静态,公共类)是this改性剂.

例如,这不是扩展方法:

public static int Square(int x) { return x * x; }
Run Code Online (Sandbox Code Playgroud)

但这是:

public static int Square(this int x) { return x * x; }
Run Code Online (Sandbox Code Playgroud)

那么Reflection如果可能的话,如何区分两种使用方法或其他方法呢?

Jon*_*eet 7

它不完全相同,但您可以检查该方法是否已ExtensionAttribute应用于该方法.

var method = type.GetMethod("Square");
if (method.IsDefined(typeof(ExtensionAttribute), false))
{
    // Yup, it's an extension method
}
Run Code Online (Sandbox Code Playgroud)

现在我说它不完全相同,因为你可以写:

[Extension]
public static int Square(int x) { return x * x; }
Run Code Online (Sandbox Code Playgroud)

...并且编译器仍然会将其作为扩展方法.所以这确实检测它是否是一个扩展方法(假设它是在静态顶级非泛型类型中)但它没有检测到源代码是否this在第一个参数上有修饰符.