C# Extension Method for Object

后端 未结 6 1903
萌比男神i
萌比男神i 2021-02-06 22:22

Is it a good idea to use an extension method on the Object class?

I was wondering if by registering this method if you were incurring a performance penalty as it would b

相关标签:
6条回答
  • 2021-02-06 23:00

    Is it a good idea to use an extension method on the Object class?

    Yes, there are cases where it is a great idea in fact.Tthere is no performance penalty whatsoever by using an extension method on the Object class. As long as you don't call this method the performance of your application won't be affected at all.

    For example consider the following extension method which lists all properties of a given object and converts it to a dictionary:

    public static IDictionary<string, object> ObjectToDictionary(object instance)
    {
        var dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        if (instance != null)
        {
            foreach (var descriptor in TypeDescriptor.GetProperties(instance))
            {
                object value = descriptor.GetValue(instance);
                dictionary.Add(descriptor.Name, value);
            }
        }
        return dictionary;
    }
    
    0 讨论(0)
  • 2021-02-06 23:01

    This is an old question but I don't see any answers here that try to reuse the existing find function for objects that are active. Here's a succinct extension method with an optional overload for finding inactive objects.

    using System.Linq;
    
    namespace UnityEngine {
    
    public static class GameObjectExtensionMethods {
    
        public static GameObject Find(this GameObject gameObject, string name, 
            bool inactive = false) {
    
           if (inactive)
              return Resources.FindObjectsOfTypeAll<GameObject>().Where(
                 a => a.name == name).FirstOrDefault();
           else
               return GameObject.Find(name);
        }
      }
    }
    

    If you use this function within the Update method you might consider changing the LINQ statement with an array for loop traversal to eliminate garbage generation.

    0 讨论(0)
  • 2021-02-06 23:08

    There will be no performance penalty as it doesn't attach to every type in the system, it's just available to be called on any type in the system. All that will happen is that the method will show on every single object in intellisense.

    The question is: do you really need it to be on object, or can it be more specific. If it needs to be on object, the make it for object.

    0 讨论(0)
  • 2021-02-06 23:09

    In addition to another answers:

    there would be no performance penalty because extension methods is compiler feature. Consider following code:

    public static class MyExtensions
    {
        public static void MyMethod(this object) { ... }
    } 
    
    object obj = new object();
    obj.MyMethod();
    

    The call to MyMethod will be actually compiled to:

    MyExtensions.MyMethod(obj);
    
    0 讨论(0)
  • 2021-02-06 23:14

    If you truly intend to extend every object, then doing so is the right thing to do. However, if your extension really only applies to a subset of objects, it should be applied to the highest hierarchical level that is necessary, but no more.

    Also, the method will only be available where your namespace is imported.

    I have extended Object for a method that attempts to cast to a specified type:

    public static T TryCast<T>(this object input)
    {
        bool success;
        return TryCast<T>(input, out success);
    }
    

    I also overloaded it to take in a success bool (like TryParse does):

    public static T TryCast<T>(this object input, out bool success)
    {
        success = true;
        if(input is T)
            return (T)input;
        success = false;
        return default(T);
    }
    

    I have since expanded this to also attempt to parse input (by using ToString and using a converter), but that gets more complicated.

    0 讨论(0)
  • 2021-02-06 23:18

    The following example demonstrates the extension method in use.

    namespace NamespaceName
    {
    public static class CommonUtil
    {
        public static string ListToString(this IList list)
        {
            StringBuilder result = new StringBuilder("");
    
            if (list.Count > 0)
            {
                result.Append(list[0].ToString());
                for (int i = 1; i < list.Count; i++)
                    result.AppendFormat(", {0}", list[i].ToString());
            }
            return result.ToString();
        }
      }
    }
    

    The following example demonstrates how this method can be used.

    var _list = DataContextORM.ExecuteQuery<string>("Select name from products").ToList();
    string result = _list.ListToString();
    
    0 讨论(0)
提交回复
热议问题