Search Results

Search found 1787 results on 72 pages for 'reflection emit'.

Page 10/72 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How can I add reflection to a C++ application?

    - by Nick
    I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?

    Read the article

  • How can a property resolve its own name and type with reflection?

    - by Tim Santeford
    Is there a way for a property to access its own name and type at runtime using reflection? I want to access this info without hard coding the name or index of the property in the class. Simple Example Code: Private ReadOnly Property MyProperyName() As String Get Console.WriteLine((Get Current Property Info).Type.ToString) Console.WriteLine((Get Current Property Info).Name) Return "" End Get End Property Expected output: System.String MyPropertyName

    Read the article

  • A simple Dynamic Proxy

    - by Abhijeet Patel
    Frameworks such as EF4 and MOQ do what most developers consider "dark magic". For instance in EF4, when you use a POCO for an entity you can opt-in to get behaviors such as "lazy-loading" and "change tracking" at runtime merely by ensuring that your type has the following characteristics: The class must be public and not sealed. The class must have a public or protected parameter-less constructor. The class must have public or protected properties Adhere to this and your type is magically endowed with these behaviors without any additional programming on your part. Behind the scenes the framework subclasses your type at runtime and creates a "dynamic proxy" which has these additional behaviors and when you navigate properties of your POCO, the framework replaces the POCO type with derived type instances. The MOQ framework does simlar magic. Let's say you have a simple interface:   public interface IFoo      {          int GetNum();      }   We can verify that the GetNum() was invoked on a mock like so:   var mock = new Mock<IFoo>(MockBehavior.Default);   mock.Setup(f => f.GetNum());   var num = mock.Object.GetNum();   mock.Verify(f => f.GetNum());   Beind the scenes the MOQ framework is generating a dynamic proxy by implementing IFoo at runtime. the call to moq.Object returns the dynamic proxy on which we then call "GetNum" and then verify that this method was invoked. No dark magic at all, just clever programming is what's going on here, just not visible and hence appears magical! Let's create a simple dynamic proxy generator which accepts an interface type and dynamically creates a proxy implementing the interface type specified at runtime.     public static class DynamicProxyGenerator   {       public static T GetInstanceFor<T>()       {           Type typeOfT = typeof(T);           var methodInfos = typeOfT.GetMethods();           AssemblyName assName = new AssemblyName("testAssembly");           var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);           var moduleBuilder = assBuilder.DefineDynamicModule("testModule", "test.dll");           var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);              typeBuilder.AddInterfaceImplementation(typeOfT);           var ctorBuilder = typeBuilder.DefineConstructor(                     MethodAttributes.Public,                     CallingConventions.Standard,                     new Type[] { });           var ilGenerator = ctorBuilder.GetILGenerator();           ilGenerator.EmitWriteLine("Creating Proxy instance");           ilGenerator.Emit(OpCodes.Ret);           foreach (var methodInfo in methodInfos)           {               var methodBuilder = typeBuilder.DefineMethod(                   methodInfo.Name,                   MethodAttributes.Public | MethodAttributes.Virtual,                   methodInfo.ReturnType,                   methodInfo.GetParameters().Select(p => p.GetType()).ToArray()                   );               var methodILGen = methodBuilder.GetILGenerator();               methodILGen.EmitWriteLine("I'm a proxy");               if (methodInfo.ReturnType == typeof(void))               {                   methodILGen.Emit(OpCodes.Ret);               }               else               {                   if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)                   {                       MethodInfo getMethod = typeof(Activator).GetMethod(/span>"CreateInstance",new Type[]{typeof((Type)});                                               LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);                       methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);                       methodILGen.Emit(OpCodes.Call, typeofype).GetMethod("GetTypeFromHandle"));  ));                       methodILGen.Emit(OpCodes.Callvirt, getMethod);                       methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);                                                              }                 else                   {                       methodILGen.Emit(OpCodes.Ldnull);                   }                   methodILGen.Emit(OpCodes.Ret);               }               typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);           }                     Type constructedType = typeBuilder.CreateType();           var instance = Activator.CreateInstance(constructedType);           return (T)instance;       }   }   Dynamic proxies are created by calling into the following main types: AssemblyBuilder, TypeBuilder, Modulebuilder and ILGenerator. These types enable dynamically creating an assembly and emitting .NET modules and types in that assembly, all using IL instructions. Let's break down the code above a bit and examine it piece by piece                Type typeOfT = typeof(T);              var methodInfos = typeOfT.GetMethods();              AssemblyName assName = new AssemblyName("testAssembly");              var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);              var moduleBuilder = assBuilder.DefineDynamicModule("testModule", "test.dll");              var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);   We are instructing the runtime to create an assembly caled "test.dll"and in this assembly we then emit a new module called "testModule". We then emit a new type definition of name "typeName"Proxy into this new module. This is the definition for the "dynamic proxy" for type T                 typeBuilder.AddInterfaceImplementation(typeOfT);               var ctorBuilder = typeBuilder.DefineConstructor(                         MethodAttributes.Public,                         CallingConventions.Standard,                         new Type[] { });               var ilGenerator = ctorBuilder.GetILGenerator();               ilGenerator.EmitWriteLine("Creating Proxy instance");               ilGenerator.Emit(OpCodes.Ret);   The newly created type implements type T and defines a default parameterless constructor in which we emit a call to Console.WriteLine. This call is not necessary but we do this so that we can see first hand that when the proxy is constructed, when our default constructor is invoked.   var methodBuilder = typeBuilder.DefineMethod(                      methodInfo.Name,                      MethodAttributes.Public | MethodAttributes.Virtual,                      methodInfo.ReturnType,                      methodInfo.GetParameters().Select(p => p.GetType()).ToArray()                      );   We then iterate over each method declared on type T and add a method definition of the same name into our "dynamic proxy" definition     if (methodInfo.ReturnType == typeof(void))   {       methodILGen.Emit(OpCodes.Ret);   }   If the return type specified in the method declaration of T is void we simply return.     if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)   {                               MethodInfo getMethod = typeof(Activator).GetMethod("CreateInstance",                                                         new Type[]{typeof(Type)});                               LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);                                                     methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);       methodILGen.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));       methodILGen.Emit(OpCodes.Callvirt, getMethod);       methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);   }   If the return type in the method declaration of T is either a value type or an enum, then we need to create an instance of the value type and return that instance the caller. In order to accomplish that we need to do the following: 1) Get a handle to the Activator.CreateInstance method 2) Declare a local variable which represents the Type of the return type(i.e the type object of the return type) specified on the method declaration of T(obtained from the MethodInfo) and push this Type object onto the evaluation stack. In reality a RuntimeTypeHandle is what is pushed onto the stack. 3) Invoke the "GetTypeFromHandle" method(a static method in the Type class) passing in the RuntimeTypeHandle pushed onto the stack previously as an argument, the result of this invocation is a Type object (representing the method's return type) which is pushed onto the top of the evaluation stack. 4) Invoke Activator.CreateInstance passing in the Type object from step 3, the result of this invocation is an instance of the value type boxed as a reference type and pushed onto the top of the evaluation stack. 5) Unbox the result and place it into the local variable of the return type defined in step 2   methodILGen.Emit(OpCodes.Ldnull);   If the return type is a reference type then we just load a null onto the evaluation stack   methodILGen.Emit(OpCodes.Ret);   Emit a a return statement to return whatever is on top of the evaluation stack(null or an instance of a value type) back to the caller     Type constructedType = typeBuilder.CreateType();   var instance = Activator.CreateInstance(constructedType);   return (T)instance;   Now that we have a definition of the "dynamic proxy" implementing all the methods declared on T, we can now create an instance of the proxy type and return that out typed as T. The caller can now invoke the generator and request a dynamic proxy for any type T. In our example when the client invokes GetNum() we get back "0". Lets add a new method on the interface called DayOfWeek GetDay()   public interface IFoo      {          int GetNum();          DayOfWeek GetDay();      }   When GetDay() is invoked, the "dynamic proxy" returns "Sunday" since that is the default value for the DayOfWeek enum This is a very trivial example of dynammic proxies, frameworks like MOQ have a way more sophisticated implementation of this paradigm where in you can instruct the framework to create proxies which return specified values for a method implementation.

    Read the article

  • Reflection Permission problems when using the GSON library in a applet.

    - by mridang
    I'm writing an Applet that makes some JSON-RPC calls. I'm using the Google JSON library (GSON) to cast the response JSON into a class. Thsi seems to work fine as is but when I use this code in my Applet, I'm hit with a java.lang.reflect.reflectpermission. From what I read on this thread on SO, it seems that since GSON uses Reflection, I cannot use it in Applets unless I explicitly modify the security policy. How can I get around this? I've created a bunch of classes in my application and was using the Gson.fromJson method to cast it into the class. Is there any way to achieve the same functionality without having to re-write half my code. (The complexity of dealing with JSON in Java seems to be in a league of its own!) Thanks in advance guys.

    Read the article

  • Differentiate generic methods by type parameters only using reflection?

    - by Brian Vallelunga
    I'm trying to use reflection to get a specific MethodInfo of a class, but am unsure how to differentiate between the two following methods: public class Test { public IBar<T1> Foo<T1>(); public IBar<T1, T2> Foo<T1, T2>(); } How can I get a reference to the different Foo methods, assuming I know the number of type parameters? Just calling typeof(Test).GetMethod("Foo") will throw an exception that the method name is ambiguous and there aren't a differing number of parameters to check.

    Read the article

  • Reflection and the params Keyword

    - by Robert May
    I’ve had to look this up a couple of times, and there’s not much out there, so I end up guessing the same answer over and over. When using MethodBase.GetParameters() to get an array of ParameterInfo object, I often want to get a count of the number of parameters that are out, optional, params, etc.  For out and optional, you can simply check ParameterInfo.IsOut or ParameterInfo.IsOptional or any number of other “Attributes”. However, for params, there isn’t a property on ParameterInfo.  Instead, you have to do this: info.GetCustomAttributes(typeof(ParamArrayAttribute), true) This will get you a set of all of the attributes that are the ParamArrayAttribute, which you can then turn into a linq statement that looks like this: methodParameters.Count(info => info.GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0); Which, assuming that methodParameters is the result of MethodBase.GetParameters, will give you a count of the number of parameters that have the params keyword.  Of course, there can be only one, but who’s counting! Now, hopefully, the next time I try to look this up, my own blog will get the values. Technorati Tags: Reflection

    Read the article

  • What are the use cases for this static reflection code?

    - by Maslow
    This is Oliver Hanappi's static reflection code he posted on stackoverflow private static string GetMemberName(Expression expression) { switch (expression.NodeType) { case ExpressionType.MemberAccess: var memberExpression = (MemberExpression)expression; var supername = GetMemberName(memberExpression.Expression); if (String.IsNullOrEmpty(supername)) return memberExpression.Member.Name; return String.Concat(supername, '.', memberExpression.Member.Name); case ExpressionType.Call: var callExpression = (MethodCallExpression)expression; return callExpression.Method.Name; case ExpressionType.Convert: var unaryExpression = (UnaryExpression)expression; return GetMemberName(unaryExpression.Operand); case ExpressionType.Parameter: return String.Empty; default: throw new ArgumentException("The expression is not a member access or method call expression"); } } I have the public wrapper methods: public static string Name<T>(Expression<Action<T>> expression) { return GetMemberName(expression.Body); } public static string Name<T>(Expression<Func<T, object>> expression) { return GetMemberName(expression.Body); } then added my own method shortcuts public static string ClassMemberName<T>(this T sourceType,Expression<Func<T,object>> expression) { return GetMemberName(expression.Body); } public static string TMemberName<T>(this IEnumerable<T> sourceList, Expression<Func<T,object>> expression) { return GetMemberName(expression.Body); } What are examples of code that would necessitate or take advantage of the different branches in the GetMemberName(Expression expression) switch? what all is this code capable of making strongly typed?

    Read the article

  • Associate "Code/Properties/Stuff" with Fields in C# without reflection. I am too indoctrinated by J

    - by AlexH
    I am building a library to automatically create forms for Objects in the project that I am working on. The codebase is in C#, and essentially we have a HUGE number of different objects to store information about different things. If I send these objects to the client side as JSON, it is easy enough to programatically inspect them to generate a form for all of the properties. The problem is that I want to be able to create a simple way of enforcing permissions and doing validation on the client side. It needs to be done on a field by field level. In javascript I would do this by creating a parallel object structure, which had some sort of { permissions : "someLevel", validator : someFunction } object at the nodes. With empty nodes implying free permissions and universal validation. This would let me simply iterate over the new object and the permissions object, run the check, and deal with the result. Because I am overfamilar with the hammer that is javascript, this is really the only way that I can see to deal with this problem. My first implementation thus uses reflection to let me treat objects as dictionaries, that can be programatically iterated over, and then I just have dictionaries of dictionaries of PermissionRule objects which can be compared with. Very javascripty. Very awkward. Is there some better way that I can do this? Essentially a way to associate a data set with each property, and then iterate over those properties. Or else am I Doing It Wrong?

    Read the article

  • Java reflection Method invocations yield result faster than Fields?

    - by omerkudat
    I was microbenchmarking some code (please be nice) and came across this puzzle: when reading a field using reflection, invoking the getter Method is faster than reading the Field. Simple test class: private static final class Foo { public Foo(double val) { this.val = val; } public double getVal() { return val; } public final double val; // only public for demo purposes } We have two reflections: Method m = Foo.class.getDeclaredMethod("getVal", null); Field f = Foo.class.getDeclaredField("val"); Now I call the two reflections in a loop, invoke on the Method, and get on the Field. A first run is done to warm up the VM, a second run is done with 10M iterations. The Method invocation is consistently 30% faster, but why? Note that getDeclaredMethod and getDeclaredField are not called in the loop. They are called once and executed on the same object in the loop. I also tried some minor variations: made the field non-final, transitive, non-public, etc. All of these combinations resulted in statistically similar performance. Edit: This is on WinXP, Intel Core2 Duo, Sun JavaSE build 1.6.0_16-b01, running under jUnit4 and Eclipse.

    Read the article

  • Getting the constructor of an Interface Type through reflection?

    - by Will Marcouiller
    I have written a generic type: IDirectorySource<T> where T : IDirectoryEntry, which I'm using to manage Active Directory entries through my interfaces objects: IGroup, IOrganizationalUnit, IUser. So that I can write the following: IDirectorySource<IGroup> groups = new DirectorySource<IGroup>(); // Where IGroup implements `IDirectoryEntry`, of course.` foreach (IGroup g in groups.ToList()) { listView1.Items.Add(g.Name).SubItems.Add(g.Description); } From the IDirectorySource<T>.ToList() methods, I use reflection to find out the appropriate constructor for the type parameter T. However, since T is given an interface type, it cannot find any constructor at all! Of course, I have an internal class Group : IGroup which implements the IGroup interface. No matter how hard I have tried, I can't figure out how to get the constructor out of my interface through my implementing class. [DirectorySchemaAttribute("group")] public interface IGroup { } internal class Group : IGroup { internal Group(DirectoryEntry entry) { NativeEntry = entry; Domain = NativeEntry.Path; } // Implementing IGroup interface... } Within the ToList() method of my IDirectorySource<T> interface implementation, I look for the constructor of T as follows: internal class DirectorySource<T> : IDirectorySource<T> { // Implementing properties... // Methods implementations... public IList<T> ToList() { Type t = typeof(T) // Let's assume we're always working with the IGroup interface as T here to keep it simple. // So, my `DirectorySchema` property is already set to "group". // My `DirectorySearcher` is already instantiated here, as I do it within the DirectorySource<T> constructor. Searcher.Filter = string.Format("(&(objectClass={0}))", DirectorySchema) ConstructorInfo ctor = null; ParameterInfo[] params = null; // This is where I get stuck for now... Please see the helper method. GetConstructor(out ctor, out params, new Type() { DirectoryEntry }); SearchResultCollection results = null; try { results = Searcher.FindAll(); } catch (DirectoryServicesCOMException ex) { // Handling exception here... } foreach (SearchResult entry in results) entities.Add(ctor.Invoke(new object() { entry.GetDirectoryEntry() })); return entities; } } private void GetConstructor(out ConstructorInfo constructor, out ParameterInfo[] parameters, Type paramsTypes) { Type t = typeof(T); ConstructorInfo[] ctors = t.GetConstructors(BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod); bool found = true; foreach (ContructorInfo c in ctors) { parameters = c.GetParameters(); if (parameters.GetLength(0) == paramsTypes.GetLength(0)) { for (int index = 0; index < parameters.GetLength(0); ++index) { if (!(parameters[index].GetType() is paramsTypes[index].GetType())) found = false; } if (found) { constructor = c; return; } } } // Processing constructor not found message here... } My problem is that T will always be an interface, so it never finds a constructor. Might somebody guide me to the right path to follow in this situation?

    Read the article

  • How to create contracts in python

    - by recluze
    I am just moving to python from Java and have a question about the way the two do things. My question relates to contracts. An example: an application defines an interface that all plugins must implement and then the main application can call it. In Java: public interface IPlugin { public Image modify(Image img); } public class MainApp { public main_app_logic() { String pluginName = "com.example.myplugin"; IPlugin x = (IPlugin) Class.forName(pluginName); x.modify(someimg); } } The plugin implements the interface and we use reflection in main app to call it. That way, there's a contract between the main app and the plugin that both can refer to. How does one go about doing something similar in Python? And also, which approach is better? p.s. I'm not posting this on SO because I'm much more concerned with the philosophy behind the two approaches.

    Read the article

  • Understanding how texCUBE works and writing cubemaps properly into a cube rendertarget

    - by cubrman
    My goal is to create accurate reflections, sampled from a dynamic cubemap, for specific 3d objects (mostly lights) in XNA 4.0. To sample the cubemap I compute the 3d reflection vector in a classic way: half3 ReflectionVec = reflect(-directionToCamera, Normal.rgb); I then use the vector to get the actual reflected color: half3 ReflectionCol = texCUBElod(ReflectionSampler, float4(ReflectionVec, 0)); The cubemap I am sampling from is a RenderTarget with 6 flat faces. So my question is, given the 3d world position of an arbitrary 3d object, how can I make sure that I get accurate reflections of this object, when I re-render the cubemap. Should I build the ViewProjection matrix in a specific way? Or is there any other approach?

    Read the article

  • HLSL How to flip geometry horizontally

    - by cubrman
    I want to flip my asymmetric 3d model horizontally in the vertex shader alongside an arbitrary plane parallel to the YZ plane. This should switch everything for the model from the left hand side to the right hand side (like flipping it in Photoshop). Doing it in pixel shader would be a huge computational cost (extra RT, more fullscreen samples...), so it must be done in the vertex shader. Once more: this is NOT reflection, i need to flip THE WHOLE MODEL. I thought I could simply do the following: Turn off culling. Run the following code in the vertex shader: input.Position = mul(input.Position, World); // World[3][0] holds x value of the model's pivot in the World. if (input.Position.x <= World[3][0]) input.Position.x += World[3][0] - input.Position.x; else input.Position.x -= input.Position.x - World[3][0]; ... The model is never drawn. Where am I wrong? I presume that messes up the index buffer. Can something be done about it? P.S. it's INSANELY HARD to format code here. Thanks to Panda I found my problem. SOLUTION: // Do thins before anything else in the vertex shader. Position.x *= -1; // To invert alongside the object's YZ plane.

    Read the article

  • Input/Output console window in XNA

    - by Will Bagley
    I am currently making a simple game in XNA but am at a point where testing various aspect gets a bit tricky, especially when you have to wait till you have 1000 score to see if your animation is playing correctly etc. Of course i could just edit the starting variable in the code before I launched but I have recently been interested in trying to implement a console style window which can print out values and take input to alter public variables during run-time. I am aware that VS has the immediate window which achieves a similar thing but i would prefer mine is an actual part of the game with the intention that the user may have limited access to it in the future. Some of the key things i have yet to find an answer to after looking around for a while are: how i would support free text entry how i would access variables during runtime how i would edit these variable I have also read about using a property grid from windows form aps (and partially reflection) which looked like it could simplify a lot of things but i am not sure how I would get that running inside my XNA game window or how i would get it to not look out of place (as the visual aspect of is seems to be aimed just for development time viewing). All in all I'm quite open to any suggestions on how to approach this task as currently I'm not sure where to start. Thanks in advance.

    Read the article

  • .Net reflection to get description of class / property etc?

    - by ClarkeyBoy
    Hi, I know its unlikely but I was wondering if there is any way to get the comments (i.e. the bits after the ''') of a class or property..? I have managed to get a list of properties of a class using the PropertyInfo class but I cant find a way to get the comments / description.. I need it for a guide I am writing for the administrators of my site - it would be great if it could automatically update if new properties are added, so there is no need to worry about updating it in the future too much. Anyone know how to do this? Thanks in advance. Regards, Richard

    Read the article

  • Using reflection to change static final File.separatorChar for unit testing?

    - by Stefan Kendall
    Specifically, I'm trying to create a unit test for a method which requires uses File.separatorChar to build paths on windows and unix. The code must run on both platforms, and yet I get errors with JUnit when I attempt to change this static final field. Anyone have any idea what's going on? Field field = java.io.File.class.getDeclaredField( "separatorChar" ); field.setAccessible(true); field.setChar(java.io.File.class,'/'); When I do this, I get IllegalAccessException: Can not set static final char field java.io.File.separatorChar to java.lang.Character Thoughts?

    Read the article

  • .Net reflection to get developers comments about class / property etc?

    - by ClarkeyBoy
    Hi, I know its unlikely but I was wondering if there is any way to get the comments (i.e. the bits after the ''') of a class or property..? I have managed to get a list of properties of a class using the PropertyInfo class but I cant find a way to get the comments / description.. I need it for a guide I am writing for the administrators of my site - it would be great if it could automatically update if new properties are added, so there is no need to worry about updating it in the future too much. Anyone know how to do this? Thanks in advance. Regards, Richard

    Read the article

  • How to get MinValue/MaxValue of a certain ValueType via reflection?

    - by marco.ragogna
    I need to this at runtime. I checked using Reflector and value types line like Int16, for example, should contain <Serializable, StructLayout(LayoutKind.Sequential), ComVisible(True)> _ Public Structure Int16 Implements IComparable, IFormattable, IConvertible, IComparable(Of Short), IEquatable(Of Short) Public Const MaxValue As Short = &H7FFF Public Const MinValue As Short = -32768 End Structure But the following code is not working Dim dummyValue = Activator.CreateInstance(GetType(UInt16)) Dim minValue As IComparable = DirectCast(dummyValue.GetType.GetProperty("MinValue").GetValue(dummyValue, Nothing), IComparable) any idea how to solve?

    Read the article

  • How to use reflection to call a method and pass parameters whose types are unknown at compile time?

    - by MandoMando
    I'd like to call methods of a class dynamically with parameter values that are "parsed" from a string input. For example: I'd like to call the following program with these commands: c:myprog.exe MethodA System.Int32 777 c:myprog.exe MethodA System.float 23.17 c:myprog.exe MethodB System.Int32& 777 c:myprog.exe MethodC System.Int32 777 System.String ThisCanBeDone static void Main(string[] args) { ClassA aa = new ClassA(); System.Type[] types = new Type[args.Length / 2]; object[] ParamArray = new object[types.Length]; for (int i=0; i < types.Length; i++) { types[i] = System.Type.GetType(args[i*2 + 1]); // LINE_X: this will obviously cause runtime error invalid type/casting ParamArray[i] = args[i*2 + 2]; MethodInfo callInfo = aa.GetType().GetMethod(args[0],types); callInfo.Invoke(aa, ParamArray); } // In a non-changeable classlib: public class ClassA { public void MethodA(int i) { Console.Write(i.ToString()); } public void MethodA(float f) { Console.Write(f.ToString()); } public void MethodB(ref int i) { Console.Write(i.ToString()); i++; } public void MethodC(int i, string s) { Console.Write(s + i.ToString()); } public void MethodA(object o) { Console.Write("Argg! Type Trapped!"); } } "LINE_X" in the above code is the sticky part. For one, I have no idea how to assign value to a int or a ref int parameter even after I create it using Activator.CreatInstance or something else. The typeConverter does come to mind, but then that requires an explicit compile type casting as well. Am I looking at CLR with JavaScript glasses or there is way to do this?

    Read the article

  • How to use reflection to get a default constructor?

    - by Qwertie
    I am writing a library that generates derived classes of abstract classes dynamically at runtime. The constructor of the derived class needs a MethodInfo of the base class constructor so that it can invoke it. However, for some reason Type.GetConstructor() returns null. For example: abstract class Test { public abstract void F(); } public static void Main(string[] args) { ConstructorInfo constructor = typeof(Test).GetConstructor( BindingFlags.NonPublic | BindingFlags.Public, null, System.Type.EmptyTypes, null); // returns null! } Note that GetConstructor returns null even if I explicitly declare a constructor in Test, and even if Test is not abstract.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >