C# 对位于独立程序集中的枚举扩展方法的思考

C# 对位于独立程序集中的枚举扩展方法的思考,c#,reflection,enums,extension-methods,C#,Reflection,Enums,Extension Methods,我有: public enum ActivityStatus { All = 0, Active = 1, Inactive = 2 } public static class MyClass { public static string Test(this ActivityStatus _value) { return _value + "111"; } } 和typeof(ActivityStatus).GetMethods()不包含测试方法。我甚至试图

我有:

public enum ActivityStatus
{
    All = 0,
    Active = 1,
    Inactive = 2
}

public static class MyClass
{
    public static string Test(this ActivityStatus _value) { return _value + "111"; } 
}

typeof(ActivityStatus).GetMethods()不包含测试方法。我甚至试图把所有的东西都放在同一个集合中,但仍然没有成功。我哪里错了?

你为什么期望它会在那里?枚举没有方法。扩展方法位于class
MyClass
中。您可以使用不同的语法调用它,因此它看起来就像是
ActivityStatus
的一个方法,这一事实就是上面的语法糖

typeof(MyClass).GetMethods()

如果使用正确的绑定标志(public,static),则应返回该方法。

扩展方法只是静态方法,编译器将转换此调用

yourEnum.Test();
致:

因此,为了通过反射获得
Test
方法信息,您需要检查
MyClass
ActivityStatus
只是其中的一个参数

var testMethodInfo = typeof(MyClass).GetMethod("Test");
var firstParameter = testMethodInfo.GetParameters()[0];

Console.WriteLine (firstParameter.ParameterType + " " + firstParameter.Name);
印刷品:

ActivityStatus _value
如果要获取特定程序集中类型的所有扩展方法,可以使用以下代码:

var extensionMethodsForActivityStatus = 
        typeof(ActivityStatus) //type from assembly to search
           .Assembly  //pick an assembly
           .GetTypes() //get all types there 
           .SelectMany(t => t.GetMethods()) //get all methods for that type
           .Where(m => m.GetParameters().Any() &&
                       m.GetParameters().First().ParameterType == typeof(ActivityStatus)) //check if first parameter is our enum
           .Where(m => m.IsDefined(typeof(ExtensionAttribute), true)); //check if the method is an extension method

foreach(var extensionMethod in extensionMethodsForActivityStatus)
    Console.WriteLine(extensionMethod.Name); //prints only Test
var extensionMethodsForActivityStatus = 
        typeof(ActivityStatus) //type from assembly to search
           .Assembly  //pick an assembly
           .GetTypes() //get all types there 
           .SelectMany(t => t.GetMethods()) //get all methods for that type
           .Where(m => m.GetParameters().Any() &&
                       m.GetParameters().First().ParameterType == typeof(ActivityStatus)) //check if first parameter is our enum
           .Where(m => m.IsDefined(typeof(ExtensionAttribute), true)); //check if the method is an extension method

foreach(var extensionMethod in extensionMethodsForActivityStatus)
    Console.WriteLine(extensionMethod.Name); //prints only Test