如果有方法/扩展方法,则调用它。

3
我正在为字典制作一个ToDebugString()方法,但我还希望它可以使用该类型的任何项如果该类型有可用的ToDebugString()方法的话。
由于ToDebugString()有时作为本机.NET类型的扩展方法实现(如字典和列表),因此我在检查方法是否存在时遇到了麻烦。我只将扩展方法放在一个称为ExtensionMethods的单个类中,这样我就只需要搜索一个附加类。
关注点如下:
ToDebugString()抱怨类型参数。另外,由于Value是泛型类型,它不会自动建议ToDebugString()方法,因此我假设那里也存在问题。
kv.Value.HasMethod("ToDebugString") ? kv.Value.ToDebugString() : kv.Value.ToString()

如果我不使用本地的.NET类型,实现一个通用接口可能是解决方案。
以下是完整代码片段:
// via: https://dev59.com/a2435IYBdhLWcg3w9FHi#5114514
public static bool HasMethod(this object objectToCheck, string methodName) {
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

// Convert Dictionary to string
// via: https://dev59.com/dm025IYBdhLWcg3wnnYw#5899291
public static string ToDebugString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
    return "{" + string.Join(", ", dictionary.Select(kv => kv.Key.ToString() + "=" + (kv.Value.HasMethod("ToDebugString") ? kv.Value.ToDebugString() : kv.Value.ToString())).ToArray()) + "}";
}

此外,这里有一些我为了尝试让HasMethod()给出正确结果而做的小测试:链接

typeof(ExtensionMethods).HasMethod() 目前正在在类型 Type 上查找该方法,因为您将其作为对象传递并在其上调用 GetType(),这将返回 typeof(Type) - Dan Bryant
1
是的,但是 typeof(ExtensionMethods).GetType() == typeof(Type),所以如果你说 typeof(ExtensionMethods).GetType().GetMethod(),你是在查找类型 Type 上的方法。你需要更改你的辅助函数 HasMethod,允许直接检查类型而不是实例的类型。 - Dan Bryant
@MLM,请看一下这个答案 - https://dev59.com/ZHVC5IYBdhLWcg3wbQfA 。扩展方法不属于它们所扩展的类型,而是属于定义它们的类。 - alex.b
你试图在静态类型中使用动态类型,这是行不通的。C#支持动态类型,你可能可以在这里应用它。但是,为什么要这样做呢?编译器告诉你扩展方法不存在,并且在创建之前不会存在。你为什么想调用一个你知道不存在的函数呢? - Aaron Carlson
请将您的答案发布为答案,并将问题保留为问题。 - Tom Blodget
显示剩余4条评论
3个回答

4
您的扩展方法未被调用的原因是因为扩展方法属于定义它们的类型,所以这种调用方式:
"Hello world".MyExtensionMethod()

在幕后会被转换成:

ExtensionMethods.MyExtensionMethod("Hello world"));// "Hello world".MyExtensionMethod()

这个主题有一些代码示例,说明如何获取特定类的所有扩展方法,我稍微修改了一下代码,在此处提供按名称运行扩展方法的代码:

    // the utility code

    internal static class ExtensionMethodsHelper
    {
        private static readonly ConcurrentDictionary<Type, IDictionary<string, MethodInfo>> methodsMap = new ConcurrentDictionary<Type, IDictionary<string, MethodInfo>>();

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static MethodInfo GetExtensionMethodOrNull(Type type, string methodName)
        {
            var methodsForType = methodsMap.GetOrAdd(type, GetExtensionMethodsForType);
            return methodsForType.ContainsKey(methodName)
                ? methodsForType[methodName]
                : null;
        }

        private static IDictionary<string, MethodInfo> GetExtensionMethodsForType(Type extendedType)
        {
            // WARNING! Two methods with the same name won't work here
            // for sake of example I ignore this fact
            // but you'll have to do something with that

            return AppDomain.CurrentDomain
                            .GetAssemblies()
                            .Select(asm => GetExtensionMethods(asm, extendedType))
                            .Aggregate((a, b) => a.Union(b))
                            .ToDictionary(mi => mi.Name, mi => mi);
        }

        private static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly, Type extendedType)
        {
            var query = from type in assembly.GetTypes()
                        where type.IsSealed && !type.IsGenericType && !type.IsNested
                        from method in type.GetMethods(BindingFlags.Static
                            | BindingFlags.Public | BindingFlags.NonPublic)
                        where method.IsDefined(typeof(ExtensionAttribute), false)
                        where method.GetParameters()[0].ParameterType == extendedType
                        select method;
            return query;
        }
    }

    // example: class with extension methods


    public static class ExtensionMethods
    {
        public static string MyExtensionMethod(this string myString)
        {
            return "ranextension on string '" + myString + "'";
        }
    }

    // example: usage

    internal class Program
    {
        private static void Main()
        {
            var mi = ExtensionMethodsHelper.GetExtensionMethodOrNull(typeof(string), "MyExtensionMethod");
            if (mi != null)
            {
                Console.WriteLine(mi.Invoke(null, new object[] { "hello world" }));
            }
            else
            {
                Console.WriteLine("did't find extension method with name " + "MyExtensionMethod");
            }
        }
    }

更新
让我们看看这段代码: myTest.HasMethodOrExtensionMethod("MyExtensionMethod") ? myTest.MyExtensionMethod() :"didnotrun"

它不能编译。怎样让它工作。

  // utility code
  public static class ExtensionMethods
  {
      public static string MyExtensionMethod(this string myString)
      {
          return "ranextension on string '" + myString + "'";
      }

      public static object InvokeExtensionMethod(this object instance, string methodName, params object[] arguments)
      {
          if (instance == null) throw new ArgumentNullException("instance");

          MethodInfo mi = ExtensionMethodsHelper.GetExtensionMethodOrNull(instance.GetType(), methodName);
          if (mi == null)
          {
              string message = string.Format("Unable to find '{0}' extension method in '{1}' class.", methodName, instance);
              throw new InvalidOperationException(message);
          }

          return mi.Invoke(null, new[] { instance }.Concat(arguments).ToArray());
      }
  }

  // example usage    
  Console.WriteLine("hey".InvokeExtensionMethod("MyExtensionMethod"));

清理你的答案并使其更加精确,以便我可以接受它。我已经更新了问题,并使用了最终解决方案。 - MLM

2
理解扩展方法的关键在于它们属于声明它们的类,而不是它们扩展的类。因此,如果你在期望的扩展类上搜索扩展方法,你会发现它并不存在。
感谢aleksey.berezan的评论再次提醒我这个问题和答案,其中有一个很好的方法来获取扩展方法。
解决方案:
以下是完整清理后的解决方案。这段代码也可以在我的项目Radius:一个Unity 3D项目,在GitHub上获得
它通过检查对象类本身是否具有ToDebugString(),然后搜索ExtensionMethods类中的ToDebugString()扩展方法来工作。如果这也失败了,它就使用普通的ToString()
// Convert Dictionary to string
// via: https://dev59.com/dm025IYBdhLWcg3wnnYw#5899291
public static string ToDebugString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
    return "{" + string.Join(", ", dictionary.Select(kv => GetToDebugString(kv.Key) + "=" + GetToDebugString(kv.Value)).ToArray()) + "}";
}

static string GetToDebugString<T>(T objectToGetStringFrom)
{
    // This will try to call the `ToDebugString()` method from the class first
    // Then try to call `ToDebugString()` if it has an extension method in ExtensionMethods class
    // Otherwise just use the plain old `ToString()`

    // Get the MethodInfo
    // This will check in the class itself for the method
    var mi = objectToGetStringFrom.GetMethodOrNull("ToDebugString"); 

    string keyString = "";

    if(mi != null)
        // Get string from method in class
        keyString = (string)mi.Invoke(objectToGetStringFrom, null);
    else
    {
        // Try and find an extension method
        mi = objectToGetStringFrom.GetExtensionMethodOrNull("ToDebugString");

        if(mi != null)
            // Get the string from the extension method
            keyString = (string)mi.Invoke(null, new object[] {objectToGetStringFrom});
        else
            // Otherwise just get the normal ToString
            keyString = objectToGetStringFrom.ToString();
    }

    return keyString;
}

// ------------------------------------------------------------
// ------------------------------------------------------------

// via: https://dev59.com/ZHVC5IYBdhLWcg3wbQfA#299526
static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly, Type extendedType)
{
    var query = from type in assembly.GetTypes()
        where type.IsSealed && !type.IsGenericType && !type.IsNested
            from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
            where method.IsDefined(typeof(ExtensionAttribute), false)
            where method.GetParameters()[0].ParameterType == extendedType
            select method;
    return query;
}

public static MethodInfo GetMethodOrNull(this object objectToCheck, string methodName)
{
    // Get MethodInfo if it is available in the class
    // Usage:
    //      string myString = "testing";
    //      var mi = myString.GetMethodOrNull("ToDebugString"); 
    //      string keyString = mi != null ? (string)mi.Invoke(myString, null) : myString.ToString();

    var type = objectToCheck.GetType();
    MethodInfo method = type.GetMethod(methodName);
    if(method != null)
        return method;

    return null;
}

public static MethodInfo GetExtensionMethodOrNull(this object objectToCheck, string methodName)
{
    // Get MethodInfo if it available as an extension method in the ExtensionMethods class
    // Usage:
    //      string myString = "testing";
    //      var mi = myString.GetMethodOrNull("ToDebugString"); 
    //      string keyString = mi != null ? (string)mi.Invoke(null, new object[] {myString}); : myString.ToString();

    Assembly thisAssembly = typeof(ExtensionMethods).Assembly;
    foreach (MethodInfo methodEntry in GetExtensionMethods(thisAssembly, objectToCheck.GetType()))
        if(methodName == methodEntry.Name)
            return methodEntry;

    return null;
}

如果您的扩展方法在其他地方,请确保编辑GetExtensionMethodOrNull()中的此行:
Assembly thisAssembly = typeof(ExtensionMethods).Assembly;

-1
您调用 GetMethod 失败的原因是您要查找的方法是静态的,而且您在 GetMethod 调用中没有包含该标志。请尝试以下代码:
  public static bool HasMethod(this object objectToCheck, string methodName)
  {
     BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;

     var type = objectToCheck.GetType();
     return type.GetMethod(methodName, flags) != null;
  } 

我仍然在使用带有标志的更新函数运行所有测试时得到“未运行”结果。 - MLM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接