question

JanBarnet-1835 avatar image
0 Votes"
JanBarnet-1835 asked sreejukg answered

Net Core reflection, detect input parameter from ParameterInfo

Hello, I am developer using Visual studio for platform net core. I am testing the example on your site, copy paste from here : "https://docs.microsoft.com/en-us/dotnet/api/system.reflection.parameterinfo.attributes?view=net-5.0" . I am using the net core app 3.1 sdk & runtime. I am not able to find out why the first argument of MyMethod is not reflected as IN in attributes by the net reflection mechanism. And how to find out it by another way if exists? Thank you, Jan

dotnet-runtime
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,@JanBarnet-1835 Do you have error messages? The method can work well in my side.

0 Votes 0 ·

Give us some code. You had do to do some minor change.

0 Votes 0 ·

1 Answer

sreejukg avatar image
0 Votes"
sreejukg answered

As per the documentation from the following URL

https://docs.microsoft.com/en-us/dotnet/api/system.reflection.parameterinfo.attributes?view=net-5.0

To get the ParameterAttributes value, first get the Type. From the Type, get the ParameterInfo array. The ParameterAttributes value is within the array.
These enumerator values are dependent on optional metadata. Not all attributes are available from all compilers. See the appropriate compiler instructions to determine which enumerated values are available.

For you to check whether a parameter is In or Out, you can use the IsOut property and decide.


e.g.

  internal class Program
         {
             static void Main(string[] args)
             {
                 Console.WriteLine("Hello World!");
                 Type myType = typeof(MyClass1);
                 MethodBase myMethodBase = myType.GetMethod("MyMethod");
                 ParameterInfo[] myParameters = myMethodBase.GetParameters();
                 Console.WriteLine("\nThe method {0} has the {1} parameters :",
                               "ParameterInfo_Example.MyMethod", myParameters.Length);
                 for (int i = 0; i < myParameters.Length; i++)
                 {
                        
                     Console.WriteLine("\tThe {0} parameter is {1}",
                                                         i + 1, myParameters[i].IsOut?"Out":"In");
                 }
             }
         }
        
        
         public class MyClass1
         {
             public int MyMethod(int i, out short j, ref long k)
             {
                 j = 2;
                 return 0;
             }
         }







5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.