Question

I have a need to dynamically generate such classes:

public class SomeProxyClass
{
    public Action<some_vars> ActionName;
    public rettype InvokeActionName(some_vars)
    {
        if(this.ActionName != null)
        {
            return this.ActionName(some_vars);
        }
        return default(rettype);
    }
}
public class SomeClass
{
    public static SomeProxyClass parentProxy;
    public static rettype ActionName(some_vars)
    {
        this.parentProxy.InvokeActionName(some_vars);
    }
}

My main problem is that I don't know how to generate even such simple methods with IL instructions, so I'm looking for your help! Thank you in advance!

Was it helpful?

Solution

If you want to generate class dynamically you can use CodeDom or Reflection.Emit. CodeDom creates C# code dynamically and then compiles it whereas Reflection.emit creates MSIL for the code. If you want to write in IL you can just create this class like you do normally and then use ILDASM.exe to decompile your class into IL. Now that you know what your code should be like in IL you can generate your class dynamically using Reflection.emitsILGenerator` class. For step by step process please refer this article: http://www.codeproject.com/Articles/121568/Dynamic-Type-Using-Reflection-Emit

Hope it helps you.

OTHER TIPS

Note: Action doesn't return a value. Therefore, return this.ActionName(some_vars) will be invalid if you're expecting a value to be returned.

Here is what I come up with, and hope it help :)

public class SomeProxyClass<I,O>
{
    public Func<I, Nullable<O>> ActionName;
    public Nullable<O> InvokeActionName(I value)
    {
        if(this.ActionName != null)
        {
            return this.ActionName(value);
        }
        return null;
    }
}

public class SomeClass
{
    public static SomeProxyClass<string, int> parentProxy = new SomeProxyClass<string, int>();
    public static int? ActionName(string value)
    {
        this.parentProxy.InvokeActionName(value);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top