Code Generators or T4 Templates, are they really evil?

前端 未结 15 1389
[愿得一人]
[愿得一人] 2021-01-31 12:19

I have heard people state that Code Generators and T4 templates should not be used. The logic behind that is that if you are generating code with a generator then there is a bet

15条回答
  •  再見小時候
    2021-01-31 13:15

    I've used T4 for code generation and also Generics. Both are good, have their pros and cons, and are suited for different purposes.

    In my case, I use T4 to generate Entities, DAL and BLL based on a database schema. However, DAL and BLL reference a mini-ORM I built, based on Generics and Reflection. So I think you can use them side by side, as long as you keep in control and keep it small and simple.

    T4 generates static code, while Generics is dynamic. If you use Generics, you use Reflection which is said to be less performant than "hard-coded" solution. Of course you can cache reflection results.

    Regarding "return new T();", I use Dynamic Methods like this:

    public class ObjectCreateMethod
        {
        delegate object MethodInvoker();
        MethodInvoker methodHandler = null;
    
        public ObjectCreateMethod(Type type)
        {
            CreateMethod(type.GetConstructor(Type.EmptyTypes));
        }
    
        public ObjectCreateMethod(ConstructorInfo target)
        {
            CreateMethod(target);
        }
    
        void CreateMethod(ConstructorInfo target)
        {
            DynamicMethod dynamic = new DynamicMethod(string.Empty,
                        typeof(object),
                        new Type[0],
                        target.DeclaringType);
            ILGenerator il = dynamic.GetILGenerator();
            il.DeclareLocal(target.DeclaringType);
            il.Emit(OpCodes.Newobj, target);
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ret);
    
            methodHandler = (MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker));
        }
    
        public object CreateInstance()
        {
            return methodHandler();
        }
    }
    

    Then, I call it like this:

    ObjectCreateMethod _MetodoDinamico = new ObjectCreateMethod(info.PropertyType);
    object _nuevaEntidad = _MetodoDinamico.CreateInstance();
    

提交回复
热议问题