C# Extension Method for Object

后端 未结 6 1900
萌比男神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 ObjectToDictionary(object instance)
    {
        var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase);
        if (instance != null)
        {
            foreach (var descriptor in TypeDescriptor.GetProperties(instance))
            {
                object value = descriptor.GetValue(instance);
                dictionary.Add(descriptor.Name, value);
            }
        }
        return dictionary;
    }
    

提交回复
热议问题