How to extend a class, not an instance?

Possible duplicate:
Can you create a Static / Shared extension method?

Extension methods are great! Forgive my ignorance, but so far I have found that you can extend the class to allow methods in your instances, but not the class itself.

Here is what I am trying to do.
I have an enumeration like this:

enum ViewType
{
    Front_View,
    Back_View
}

And I already created an extension method ToDescription()to display a convenient textual representation of the view type, for example:

ViewType thisview = ViewType.Front_View;
string thisviewtext = thisview.ToDescription();  // translates to "Front View"

But later in the code, I want to analyze this translation back to a type, like this potential code, assuming that I can extend the enumeration type itself:

// !!!NOT REAL CODE YET!!!
// translate to value ViewType.FrontView
ViewType newview = ViewType.ParseFromDescription("Front View");

How to implement this extension method ParseFromDescription(string)(if possible)?

+3
3

, . , , String.IsNullOrBlank(), . String .

, ParseDescriptionToViewType(), "this" ViewType.

+2

. ViewTypeTools, . - , .

+7

Another option (kludgy) that I have not tested, but I think will work

((ViewType)null).ParseFromDescription( "Front View" );

// defined like 
public static ViewType( this ViewType me, string description )
{
    // ignore the 'this' parameter, just parse etc ...
}
0
source

Source: https://habr.com/ru/post/1765187/


All Articles