Implementing multiparameter C++ template like behaviour on C# using Policy Pattern

后端 未结 2 1556
春和景丽
春和景丽 2021-01-17 23:40

I\'m trying to implement a c++ like template with C# generics and policy pattern based on this answer

This is a sample of the pattern:

interface ISom         


        
2条回答
  •  [愿得一人]
    2021-01-18 00:01

    Tried your code, but even simple calls did not work out of box. Main problem is that MyClass contains unknown element type 'myEement' - that type cannot be deduced from function call parameters. However - if you make a generalization and omit object type - your sample will work in out of box manner:

    using System;
    using System.Collections.Generic;
    
    interface ISomePolicy 
    {
        void _doSomething(U u);
    }
    
    public class MyClass :
         ISomePolicy,
         ISomePolicy
    {
        internal object myEement { get; set; }
    
        public MyClass(object Element)
        {
            myEement = Element;
        }
    
        void ISomePolicy._doSomething(double u)
        {
            Console.WriteLine("this is double");
        }
    
        void ISomePolicy._doSomething(int u)
        {
            Console.WriteLine("this is int");
        }
    }
    
    static class MyClassExtension
    {
        public static void doSomething(this P oTh, U u) where P : ISomePolicy
        {
            oTh._doSomething(u);
        }
    }
    
    class Program
    {
        static void Main()
        {
            MyClass oClass = new MyClass(3);
            oClass.doSomething(0.5); //This works
            oClass.doSomething(1);   //This works            
            //oClass.doSomething("Will not work");
        }
    }
    

    What is up to myEement (or you probably meant myElement) - you can get's it's type at run-time if necessary.

    myElement.GetType(), or cast to it - e.g.
    if( myElement is int ) DoSomethingWithInt( (int) myElement );
    

    However - reflection always might slow down your execution. If you don't intend to create super heavy class hierarchy with huge amount of instances - then this should be sufficient for your needs.

提交回复
热议问题