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

时间:2014-05-21 16:37:12

标签: c# generics extension-methods

我正在为字典制作ToDebugString()方法,但我也希望它对任何项目使用ToDebugString()方法,如果它适用于该类型。

由于ToDebugString()有时被实现为本机.NET类型(如字典和列表)的扩展方法,因此我无法检查方法是否存在。我只将扩展方法放在一个名为ExtensionMethods的类中,所以我可能只需要在另一个类中搜索。

兴趣点在于:

ToDebugString()抱怨类型参数。此外,由于Value是通用类型,因此它不会自动建议ToDebugString()方法,所以我认为那里也存在问题。

kv.Value.HasMethod("ToDebugString") ? kv.Value.ToDebugString() : kv.Value.ToString()

如果我没有使用本机.NET类型,我认为实现一个通用接口就是解决方案。


以下是完整代码段:

// via: http://stackoverflow.com/a/5114514/796832
public static bool HasMethod(this object objectToCheck, string methodName) {
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

// Convert Dictionary to string
// via: http://stackoverflow.com/a/5899291/796832
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()) + "}";
}

同样here are a small tests我试图让HasMethod()给出正确的答案。

3 个答案:

答案 0 :(得分:3)

你的扩展方法没有被调用的原因是因为扩展方法属于定义它们的类型,所以这样的调用:

"Hello world".MyExtensionMethod()
引擎盖下的

转换为:

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

This topic有一些代码示例如何获取特定类的所有扩展方法,我已经扩展了一些代码,这里是按名称运行扩展方法的代码:

    // 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() :&#34; didnotrun&#34;

它无法编译。如何让它发挥作用。

  // 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"));

答案 1 :(得分:2)

理解扩展方法的关键是它们属于它们声明的类,而不是它们扩展的类。因此,如果您在类上搜索扩展方法,它将扩展到您期望的范围,它将不会存在。

感谢aleksey.berezan的评论再次提醒我this question and answer,它有很好的方法来获取扩展方法。

解决方案:

这是完整的清理解决方案。此代码在我的项目available here中也是Radius: a Unity 3D project, on GitHub

它通过检查对象类本身中的ToDebugString()来工作。然后在ToDebugString()类中搜索ExtensionMethods扩展方法。如果失败,它只使用正常的ToString()

// Convert Dictionary to string
// via: https://stackoverflow.com/a/5899291/796832
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://stackoverflow.com/a/299526/796832
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;

答案 2 :(得分:-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;
  }