Luca Bottani
Luca Bottani

Reputation: 113

Create a delegate when the exact type of the argument is unknown

I have some troubles to create the right delegate for this instance method:

public T AddComponent<T>() where T : Component
{
      ....
}

I am using reflection to get the specific MethodInfo and on Delegate.CreateDelegate I am getting an error binding to target method

private delegate T AddComponent<out T>();
private static AddComponent<Component> AddC { get; set; }
public void Test() 
{
  var go = new GameObject();
  var targetAddComponent =
    typeof (GameObject).GetMethods().First(m => m.Name == "AddComponent" && m.GetParameters().Length == 0);      
  AddC = (AddComponent<Component>) Delegate.CreateDelegate(typeof (AddComponent<Component>), go, targetAddComponent, true);
  ....
}

Do you have any clues on what I am doing wrong?

Upvotes: 0

Views: 171

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660024

The method info is a method info for method GameObject.AddComponent<T>, which returns T. The delegate, which you have incredibly confusingly named the same as the method, must be to a method that returns Component. What have you done to cause T to equal Component? Nothing.

Put another way: the method info is a method info to something that isn't actually a callable method until it is constructed. It's a generic pattern for making methods, not a method. Make it a method if you want to make a delegate to it. You need to supply a type argument for type parameter T in the method.

Upvotes: 2

Related Questions