An idiomatic way to reduce code replication in C #

I am new to C # (I came from C ++) and I came across a simple template that in C ++ I would allow to use templates, but the same approach does not work using C # generators.

The following code (combining C # with C ++ templates) shows my problem.

class A { /* ... */ }
class B { /* ... */ }
// C, D, ...

class W
{
    public void Update(A a) { /* ... */ }
    public void Update(B b) { /* ... */ }
    // C, D, ...
}

class X
{
    template <typename T>
    public void Update(IEnumerable<T> vs) {
        if (vs.any(vs => CreateOrUpdate(v))) {
            doStuff();
        }
    }

    template <typename T>
    public void Update(T v)
    {
        if (CreateOrUpdate(v)) {
            doStuff()
        }
    }

    template <typename T>
    private bool CreateOrUpdate(T v)
    {
        W w;
        bool updated = false;
        if (!m.TryGetValue(v.Id, out w)) {
            w = new W(v.Id);
            m.Add(w.Id, w);
            updated = true;
        }
        return w.Update(v) || updated;
    }

    private Dictionary<string, W> m;
}

Even if I A, B, ...implement an interface of type interface IId { string Id { get; } }, and I use generics public void Update<T>(IEnumerable<T> vs) : where T : IId, the code will not work because of w.Update(v)(this will require adding public bool Update(IId id)to W, but then this method will be the one that is always called).

# ++ w.Update(v) Update W. , .

+4
2

- public bool Update(IId id) W, id:

class W
{
    public bool Update(IId id)
    {
        dynamic d_id = id;
        return Update(d_id);
    }

    // ...
}

, Update , d_id dynamic.

E, IId, Update(E e), Update , . , Update(IId id) DoUpdate(IId id) DoUpdate CreateOrUpdate. , , id E .

MSDN #, .

+2

, , .

, A B IId Id . Update(W w) , , , :

private bool CreateOrUpdate(T v)
{
    W w;
    bool updated = false;
    if (!m.TryGetValue(v.Id, out w)) {
        w = new W(v.Id);
        m.Add(w.Id, w);
        updated = true;
    }
    return v.Update(w) || updated;
}

, , ( , typeof ). , . Inversion of Control.

, :

 class X<T> where T : IId

( ). , ( ).

+2
source

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


All Articles