Domanda

I have a requirement of invoke a function using reflection in c#. The following code works fine for the function which have return data type sqldatareader.

 public override void Testmethod()
   {
        SqlDataReader Reader = (SqlDataReader)method.Invoke(Activator.CreateInstance(type),new object[] {arr});
   }

But now i need to mention the return type also dynamically and depends up on that i need to invoke the function.

how can i specify the return type dynamically?

È stato utile?

Soluzione

You can get the return type of the method by

Type returnType = method.ReturnType;

Then you can compare the type, invoke the method you want and convert it's return type to the type known in compile-time (in this example, SqlDataReader)

if (returnType == typeof(SqlDataReader))
{
    SqlDataReader Reader = (SqlDataReader)method.Invoke(Activator.CreateInstance(type),new object[] {arr});
}

Do the same for other cases

else if (returnType == typeof(string))
{
    // invoke some other method and convert it's return type to a string ...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top