C# Extension Method for Object

后端 未结 6 1961
萌比男神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: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(this object input)
    {
        bool success;
        return TryCast(input, out success);
    }
    

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

    public static T TryCast(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.

提交回复
热议问题