C# 无法获取类型枚举的扩展方法

C# 无法获取类型枚举的扩展方法,c#,enums,C#,Enums,我遇到的问题是创建扩展方法 public enum TestEnum { One, Two, Three, Four } public static class EnumExtension { public static bool TestMethod(this TestEnum e) { return false; } } [TestMethod] public void TestAll() { var result = TestEnum.

我遇到的问题是创建扩展方法

public enum TestEnum
{
    One, Two, Three, Four
}

public static class EnumExtension
{
   public static bool TestMethod(this TestEnum e)
   {
       return false;
   }
}

[TestMethod]
public void TestAll()
{
    var result = TestEnum. ;   //this only gives the values of the enum (One, Two, Three, Four), there is no option to call the extension method
}
我希望上面代码中的注释真的能说明问题所在——我假设我做了一个巨大的假设,并且得到了非常错误的答案

但是,我更希望通过允许任何枚举调用此功能使其更可用。最终目标可能是

public static IEnumerable<string> ConvertToList(this Enum e)
{
     var result = new List<string>();
     foreach (string name in Enum.GetNames(typeof(e)))    //doesn't like e
     {
         result.Add(name.ToString());
     }
     return result;
}
TestEnum Val = TestEnum One;
 var b = Val.TestMethod();
List<string> enumList = Enum.GetNames(typeof(TestEnum)).ToList();
公共静态IEnumerable转换列表(此枚举e)
{
var result=新列表();
foreach(Enum.GetNames中的字符串名(typeof(e))//不喜欢e
{
Add(name.ToString());
}
返回结果;
}

扩展方法不直接作用于类型,而是作用于该类型的值

大概是

public static IEnumerable<string> ConvertToList(this Enum e)
{
     var result = new List<string>();
     foreach (string name in Enum.GetNames(typeof(e)))    //doesn't like e
     {
         result.Add(name.ToString());
     }
     return result;
}
TestEnum Val = TestEnum One;
 var b = Val.TestMethod();
List<string> enumList = Enum.GetNames(typeof(TestEnum)).ToList();

如果您需要
列表
中所有枚举的列表,则可以尝试以下操作

public static IEnumerable<string> ConvertToList(this Enum e)
{
     var result = new List<string>();
     foreach (string name in Enum.GetNames(typeof(e)))    //doesn't like e
     {
         result.Add(name.ToString());
     }
     return result;
}
TestEnum Val = TestEnum One;
 var b = Val.TestMethod();
List<string> enumList = Enum.GetNames(typeof(TestEnum)).ToList();

TestEnum
是类型。您可以执行
TestEnum.One.TestMethod()
,也可以编写一个通用的
EnumExtensions.TestMethod()
@canton7,谢谢您,但请查看我的编辑。可以将任何枚举转换为字符串列表。同样,您需要传递枚举的类型,而不是其成员之一。您不能作为扩展方法执行此操作。您将无法获得类似于
EnumType.ExtensionMethod()
的语法,无法执行此操作。您有两个选项,
EnumType.Value.ExtensionMethod()
Extensions.Something()
Extensions.Something(typeof(EnumType))
,它们都没有明显优于现有的
Enum.GetNames(typeof(EnumType))
方法。基本上,您不能这样做。可能会有帮助:因此,我无法将与
Enum
关联的值列表转换为作为扩展方法的列表?我知道如何让代码在没有扩展的情况下工作。。。