简体   繁体   中英

C#: Is it possible to have partial extension classes

I am looking to create Extension classes that extend Entity Framework Entities in a different assembly to the EF Entities. I also want to code gen some additional/generic methods in an extension methods class (using T4), then have the ability to create a partial extension methods class with additional custom methods. Is this possible.

You don't need them. Just write another extension class.

namespace Namespace1
{
    public static class MyEntityBlibblingExtensions
    {
        public void Blibble(this MyEntity self)
        {
            // ...
        }
    }
}

Then, elsewhere...

namespace Namespace2
{
    public static class MyEntityFurtlingExtensions
    {
        public void Furtle(this MyEntity self)
        {
            // ...
        }
    }
}

Anything importing Namespace1 will see the extension method Blibble() while anything importing Namespace2 will see Furtle() , and importing both will see both. They can be in different assemblies or anywhere which imports MyEntity 's namespace. So, partial extensions aren't really a valid concept. In fact, the very idea of putting extension methods inside classes is a bit of a hack as it is - a shame they couldn't unbend C#'s rules enough to let extension methods live outside of classes.

Yes - i tried it and it worked.

There is no such thing as an "extension" class - there are only extension methods which must be inside a "static" class.

You can have static partial classes.

UPDATE: Sorry I read your heading but not the text of your question. The answer is still yes, but why not just create new classes? I can't see how having a partial class really helps in this case.

The main problem I can see here is the phrase "in a different assembly". If it wasn't for that, you could just add your methods etc in an additional partial class with regular instance methods, and it would all be fine.

You can have static partial classes, however you cannot use partial classes to add to a type in another assembly. Extension methods work fine from a partial class, although note that partial classes are purely a mechanism for splitting code between different files. You could just as easily have multiple static classes for the extension methods.

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