【问题标题】:extension method on enum not being called [duplicate]未调用枚举上的扩展方法[重复]
【发布时间】:2023-03-19 22:20:02
【问题描述】:

我已经阅读了相当多的内容,并且有很多非常相似的问题的答案,但即使遵循这些问题,我也无法让它发挥作用。扩展方法是静态的,公共的,有this,在同一个命名空间中,所以不需要导入......我错过了什么?我的 C# 不太好。

namespace LDB
{

    public enum Neg { isNegated, notNegated };

    static class NegStringifier {
        public static string ToString(this Neg n) {
            string res = n switch {
                Neg.isNegated => "flowers",
                Neg.notNegated => "kittens",
                //_ => null
            };
            return res;
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine(Neg.isNegated.ToString());
            System.Console.WriteLine(Neg.notNegated.ToString());
            ...

输出:

isNegated
notNegated

先道歉,我知道这将是一件微不足道的事情,但我看不出是什么。

【问题讨论】:

  • 我想是的!请您关闭这个问题,如果您想删除它,我会同意的。

标签: c# enums


【解决方案1】:

编译器仅在找不到任何适用于方法调用的“常规”实例方法时才查找扩展方法。在这种情况下,object 类提供了一个ToString() 方法,因此那里有一个合适的方法,这就是编译器使用的方法。

如果您在扩展方法和调用代码中将ToString 更改为其他名称(例如ExtensionToString),您会看到它正在被使用。

【讨论】:

  • 所以我的方法被隐藏了。编译器将其报告为无法访问不是一回事吗?
  • @user3779002:不,它没有被隐藏——它没有被寻找。而且它并非无法访问 - 例如,您可以致电 NegStringifier.ToString(Neg.isNegated)
猜你喜欢
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
相关资源
最近更新 更多