BernardoMorais
BernardoMorais

Reputation: 631

c# - Using a 'field' as a 'type'

I have this UserControl:

public static Type typCreate;

LoadUserControl<T>()
{
   typCreate = typeof( T );
}

protected void ButtonCommand( object sender, CommandEventArgs e )
{
   x.Execute<typCreate>();
}

Considering that the method LoadUserControl is the main method and the event ButtonCommand is fired by a button on the UserControl, I'm trying to call this method on the event:

class x
{
   public static T Execute<T>() { ... }
}

The error given by VS is saying that typeCreate is a 'field' but is used like a 'type'.

How can I do this work properly?

Thanks in advance.

Upvotes: 1

Views: 643

Answers (4)

BernardoMorais
BernardoMorais

Reputation: 631

Thanks for all the answers.

I resolve the problem using Reflection.

typeof( x ).GetMethod( "Execute" ).MakeGenericMethod( typCreate ).Invoke( this, new object[] { 'PARAM' } );

Where PARAM is the parameter of the method.

Upvotes: -1

Lee Louviere
Lee Louviere

Reputation: 5262

No reflection needed

This is how you can implement that feature. You can store off the type information of a generic method by using a lambda that calls another method with the same generic parameter.

    public class Test
    {
        public static Action loadedTypeAction;

        public void LoadUserControl<T>()
        {
            loadedTypeAction = Execute<T>;
        }

        public void Execute<T>()
        {
            // do stuff
            MessageBox.Show(typeof (T).Name);
        }

        public void DoAction()
        {
            if (loadedTypeAction != null)
            {
                loadedTypeAction();
            }
        }
    }

Upvotes: 1

IS4
IS4

Reputation: 13207

using System.Reflection;

private static readonly MethodInfo x_Execute_T = typeof(x).GetMethod("Execute", BindingFlags.Public | BindingFlags.Static);
private static readonly MethodInfo BuildExecute_T = typeof(LoadUserControl).GetMethod("BuildExecute", BindingFlags.NonPublic | BindingFlags.Static);
private readonly Func<object> x_Execute;

public static Type typCreate;

public LoadUserControl(Type t)
{
    typCreate = t;
    x_Execute = (Func<object>)BuildExecute_T.MakeGenericMethod(t).Invoke(null, null);
}

private static Func<object> BuildExecute<T>()
{
    return () => ((Func<T>)Delegate.CreateDelegate(typeof(Func<T>), x_Execute_T.MakeGenericMethod(typeof(T))))();
}

protected void ButtonCommand( object sender, object e )
{
   x_Execute();
}

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190976

You will have to make your UserControl class generic as well to get compile time checking.

class Subclass<T> : UserControl
{
     protected void ButtonCommand( object sender, CommandEventArgs e )
    {
        x.Execute<T>();
    }
}

You could use reflection, but that has risk with losing compile time checking.

Upvotes: 1

Related Questions