简体   繁体   中英

Wrapping C# classes to use with polymorphism through a common interface

I've got several C# classes each with similar properties. (They're part of an SDK and their code can't be changed.)

  • Person.Name
  • Product.Name
  • Order.Name

I want to use these classes polymorphically, but they don't implement a common interface or derive from a common base class, so that's not possible. To get around this, I'd like to wrap each one in another class that does implement a common interface, and wire-up each class property to its corresponding interface property.

What would be a suitable name for the wrapper classes? Wrapper, Decorator, Adaptor, Proxy? Does this pattern have a name? Is there a better approach?

(I don't want to use dynamic duck-typing or an impromptu interface .)

它看起来像Adapter,因为您正在调整现有接口以满足特定要求。

(I don't want to use dynamic duck-typing or an impromptu interface.)

So what is wrong with a NamedObject?

public class NamedObject
{
    public string Name { get; set; }
}

It literally says what it is, nothing less, nothing more.

I'd stick with CodeCaster's idea, and perhaps with a dash of Func<T> for no other reason than I get withdrawal symptoms when I don't use angle brackets ...

public class NamedEntity
{
    public string Name { get { return _getName(); } }

    private Func<string> _getName;

    public NamedObject(Func<string> getName)
    {
        _getName = getName;
    }
}

And then call thus:

var named = new[] 
    { 
        new NamedEntity(() => person.Name),
        new NamedEntity(() => product.Name),
        new NamedEntity(() => order.Name)
    };

The added benefit with this is when the value of the property changes on the target object, it changes within the NamedEntity reference too via the Func , this means within the life span of the objects you can get away with wrapping them once. You can also do the inverse with Func s that set values as well as get, and can adapt more properties.

I am not immediately sure what pattern this represents (if any), though I would guess Adapter pattern (which is a type of wrapper pattern). However, it could also be argued to be a Proxy pattern . Not sure really.

也许你可以只更改名称空间并保留原始类的名称。

Technically, I think the most correct name would be Adapter, see this question.

Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.

You don't have abstract interface, but "similar functional role, but a different interface".

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