【问题标题】:Is there a way to determine whether a parameter has this modifier?有没有办法确定一个参数是否有这个修饰符?
【发布时间】:2014-05-23 13:22:48
【问题描述】:

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

扩展方法与其他静态方法(在 staticpublic 类中定义)的唯一区别是this 修饰符。

例如这不是扩展方法:

public static int Square(int x) { return x * x; }

但这是:

public static int Square(this int x) { return x * x; }

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

【问题讨论】:

标签: c# reflection extension-methods


【解决方案1】:

完全相同不一样,但可以检查方法是否应用了ExtensionAttribute

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

现在我说不完全一样,因为你可以写:

[Extension]
public static int Square(int x) { return x * x; }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-20
    • 2023-04-07
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多