public static void Refer(ref int a,ref int b)
in this how do i find that these variables are reference variable programatically ..how do i find their type
-
Since C# is strongly typed, you can use any
intmethods safely sinceaandbhave to beints. But if you need theTypeduring runtime, use thetypeofoperator.Type intType = typeof(a);Andy White : Does typeof work on variables? I was thinking it only worked on type names. I think for variables you have to use a.GetType() -
Do you mean you want to know via reflection that the method parameters are by-ref?
You use
MethodBase.GetParametersto get the parameters for the method, and thenParameterInfo.ParameterTypeto find the type of the parameter andType.IsByRefto check whether or not it's passed by reference.Here's a quick example:
using System; using System.Reflection; public class Test { public static void Refer(ref int a,ref int b) { } static void Main() { MethodInfo method = typeof(Test).GetMethod("Refer"); ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameter in parameters) { Console.WriteLine("{0} is ref? {1}", parameter.Name, parameter.ParameterType.IsByRef); } } }You can't do this in a "strong" way for a variable using
a.GetType()ortypeof(a)etc.GetType()finds the type of the value ofa, which is just anint.Cerebrus : Awe...some!! :-) -
You have the IsByRef property on the parameterInfo.ParameterType.
MethodInfo refer = typeof(MyClass).GetMethod("Refer"); ParameterInfo [] parameters = refer.GetParameters(); foreach (ParameterInfo parameter in parameters) { Console.WriteLine("Parameter: {0}, Type: {1}, ByRef: {2}", parameter.Name, parameter.ParameterType.Name, parameter.ParameterType.IsByRef); }
0 comments:
Post a Comment