Overloading generic methods

2019-06-15 13:29发布

问题:

When calling a generic method for storing an object there are occasionally needs to handle a specific type differently. I know that you can't overload based on constraints, but any other alternative seems to present its own problems.

public bool Save<T>(T entity) where T : class
{ ... some storage logic ... }

What I would LIKE to do is something like the following:

public bool Save<SpecificClass>(T entity)
{ ... special logic ... }

In the past our team has created 'one-off' methods for saving these classes as follows:

public bool SaveSpecificClass(SpecificClass sc)
{ ... special logic ... }

However, if you don't KNOW that function exists, and you try to use the generic (Save) then you may run into a host of problems that the 'one-off' was supposed to fix. This can be made worse if a new developer comes along, sees the problem with the generic, and decides he's going to fix it with his own one-off function.

So...

What are the options for working around this seemingly common issue?

I've looked at, and used UnitOfWork and right now that seems to be the only option that actually resolves the problem - but seems like attacking a fly with a sledgehammer.

回答1:

You could do :

public bool Save<T>(T entity) where T : class
{ ... some storage logic ... }

public bool Save(SpecificClass entity)
{ ... special logic ... }

For example:

public class SpecificClass
{
}

public class Specializer
{
    public bool GenericCalled;
    public bool SpecializedCalled;

    public bool Save<T>(T entity) where T : class
    {
        GenericCalled = true;
        return true;
    }

    public bool Save(SpecificClass entity)
    {
        SpecializedCalled = true;
        return true;
    }
}

public class Tests
{
    [Test]
    public void TestSpecialization()
    {
        var x = new Specializer();
        x.Save(new SpecificClass());
        Assert.IsTrue(x.SpecializedCalled);
        Assert.IsFalse(x.GenericCalled);
    }
}


回答2:

Because function and operator overloads involving generics are bound at compile-time rather than run-time, if code has two methods:

public bool Save<T>(T entity) ...
public bool Save(SomeClass entity) ...

then code which tries to call Save(Foo) where Foo is a variable of some generic type will always call the former overload, even when the generic type happens to be SomeClass. My suggestion to resolve that would be to define a generic interface ISaver<in T> with a non-generic method DoSave(T param). Have the class that provides the Save method implement all of the appropriate generic interfaces for the types it can handle. Then have the object's Save<T> method try to cast this to an ISaver<T>. If the cast succeeds, use the resulting ISaver<T>; otherwise perform a generic save. Provided that the class type declaration lists all of the appropriate interfaces for the types it can save, this approach will dispatch Save calls to the proper methods.



回答3:

Well basicly C# does not allow template specialization, except through inheritence like this:

interface IFoo<T> { }
class Bar { }

class FooBar : IFoo<Bar> { }

At least it does not support this during compile time. However you can use RTTI to do what you are trying to achieve:

public bool Save<T>(T entity)
{
    // Check if "entity" is of type "SpecificClass"
    if (entity is SpecificClass)
    {
        // Entity can be safely casted to "SpecificClass"
        return SaveSpecificClass((SpecificClass)entity);
    }

    // ... other cases ...
}

The is expression is pretty handy to do runtime type checks. It works similar to the following code:

if (entity.GetType() == typeof(SpecificClass))
    // ...

EDIT : It is pretty common for unknown types to use the following pattern:

if (entity is Foo)
    return DoSomethingWithFoo((Foo)entity);
else if (entity is Bar)
    return DoSomethingWithBar((Bar)entity);
else
    throw new NotSupportedException(
        String.Format("\"{0}\" is not a supported type for this method.", entity.GetType()));

EDIT 2 : As the other answers suggest overloading the method with the SpecializedClass you need to take care if you are working with polymorphism. If you are using interfaces for your repository (which is actually a good way to design the repository pattern) there are cases where overloading would lead to cases in which you are the wrong method get's called, no matter if you are passing an object of SpecializedClass to the interface:

interface IRepository
{
    bool Save<T>(T entity)
        where T : class;
}

class FooRepository : IRepository
{
    bool Save<T>(T entity)
    {
    }

    bool Save(Foo entity)
    {
    }
}

This works if you directly call FooRepository.Save with an instance of Foo:

var repository = new FooRepository();
repository.Save(new Foo());

But this does not work if you are calling the interface (e.g. if you are using patterns to implement repository creation):

IRepository repository = GetRepository<FooRepository>();
repository.Save(new Foo());  // Attention! Call's FooRepository.Save<Foo>(Foo entity) instead of FooRepository.Save(Foo entity)!

Using RTTI there's only one Save method and you'll be fine.



回答4:

Why using different names for your method?

See the following:

    public class Entity
    {
    }

    public class SpecificEntity : Entity
    {
    }

    public class Program
    {
        public static void Save<T>(T entity)
            where T : class
        {
            Console.WriteLine(entity.GetType().FullName);
        }

        public static void Save(SpecificEntity entity)
        {
            Console.WriteLine(entity.GetType().FullName);
        }

        private static void Main(string[] args)
        {
            Save(new Entity());          // ConsoleApplication13.Entity
            Save(new SpecificEntity());  // ConsoleApplication13.SpecificEntity

            Console.ReadKey();
        }
    }