开发者

C#: dynamically binding a function when template is bound to type

given a template class that will only be instantiated on say three different types A, B and C, is there a way to bind an external function call to another class based on the template type when the the template is bound to a type?

e.g.

class template<T> {
    private printer myPrinter;
    Print(T obj) {myPrinter.Print(obj);
}

class printer {
    public Print(A obj){};
    public Print(B obj){};
    public Print(C obj){};
}

Now to my understanding above will not work.

Which leaves me with t开发者_StackOverflowhe choice of

1) Writing three different classes instead of the template (having the code three times, and then the call bound statically at compile time).

2) Changing the design so that the print function is included in the objects A, B and C, and the template changes to

class template<T> where T : IPrintable {
    private printer myPrinter;
    Print(T obj) {obj.Print());
}

but this would lead to runtime dynamic resolution of the function to call and in an undesirable design as in my case the Print function belongs logically more to the printer.

3) Using the dynamic keyword, something along these lines:

class template<T> {
    private printer myPrinter;
    Print(T obj) {myPrinter.Print((dynamic)obj);
}

The binding here would happen on each function call I would imagine.

So, what I am really looking for is a solution that keeps the functions in the printer class (which eliminates two), doesn't have the code multiple times (eliminates 1) and dynamically binds the Print function not on every call but on template initialization (eliminates 3).

Basically I am thinking as soon as the template is created the runtime environment should know which function to call on every call and should not need to do a lookup every time the function gets called.

So my questions are, is my understanding as above correct? And is there a way to bind dynamically when the template is bound to a template type or a better way to do above? And what would be the overhead of using dynamic vs. multiple classes?

Thanks


Make method Print in class printer a generic method.

class Printer
{
  public Print<T>(T obj) 
  {
    if(obj is A) DoLogicForTypeA();
    else if (obj is B) DoLogicforTypeB();
    else throw new IllegalArgumentException();
  }
}

Call in template generic:

Print(T obj) {myPrinter.Print<T>(obj);

You might be able to add some where-constraints to make it work better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜