简体   繁体   中英

Is it possible to create an extension method for all classes excluding primitives in C#?

I would like to create an extension method that will work for classes only. I can write an extension method for type object , like this:

public static void SomeMethod(this object obj)
{
    // some code
}

However this will work for primitives too, I would like to disable to do something like this:

int number = 2;
number.SomeMethod();

Any ideas how can I do this, if it's possible at all?

I think you need something like this, but I will not recommend you do that only if it's not for serialization or something like that.

public static void SomeMethod<T>(this T obj) where T : class
{

}

You are going to be fighting boxing behaviour here...

Essentially you limit your type that it must be an object, but C# adds some sugar and says, thats a primitive, I can box it into an object for you and treat it like an object too!

If you have some level of subclass you can target, that might stop the behaviour you are after (as in don't target all objects but perhaps something that is IObservable, IEnumerable etc.)

The other way to defensively code this is to add an explicit type check and exception throw on your method

 if (myobject.GetTypeCode != TypeCode.Object) { throw new ArgumentException() }

Don't do it. If you have a method you want to call on a whole variety of objects, then centralize it in a function somewhere. That way some poor programmer who comes along 10 years after you will not be wondering where that weird method is located.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM