Search Results

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

Page 1/72 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Emit Knowledge - social network for knowledge sharing

    - by hajan
    Emit Knowledge, as the words refer - it's a social network for emitting / sharing knowledge from users by users. Those who can benefit the most out of this network is perhaps all of YOU who have something to share with others and contribute to the knowledge world. I've been closely communicating with the core team of this very, very interesting, brand new social network (with specific purpose!) about the concept, idea and the vision they have for their product and I can say with a lot of confidence that this network has real potential to become something from which we will all benefit. I won't speak much about that and would prefer to give you link and try it yourself - http://www.emitknowledge.com Mainly, through the past few months I've been testing this network and it is getting improved all the time. The user experience is great, you can easily find out what you need and it follows some known patterns that are common for all social networks. They have some real good ideas and plans that are already under development for the next updates of their product. You can do micro blogging or you can do regular normal blogging… it’s up to you, and the way it works, it is seamless. Here is a short Question and Answers (QA) interview I made with the lead of the team, Marijan Nikolovski: 1. Can you please explain us briefly, what is Emit Knowledge? Emit Knowledge is a brand new knowledge based social network, delivering quality content from users to users. We believe that people’s knowledge, experience and professional thoughts compose quality content, worth sharing among millions around the world. Therefore, we created the platform that matches people’s need to share and gain knowledge in the most suitable and comfortable way. Easy to work with, Emit Knowledge lets you to smoothly craft and emit knowledge around the globe. 2. How 'old' is Emit Knowledge? In hamster’s years we are almost five years old start-up :). Just kidding. We’ve released our public beta about three months ago. Our official release date is 27 of June 2012. 3. How did you come up with this idea? Everything started from a simple idea to solve a complex problem. We’ve seen that the social web has become polluted with data and is on the right track to lose its base principles – socialization and common cause. That was our start point. We’ve gathered the team, drew some sketches and started to mind map the idea. After several idea refactoring’s Emit Knowledge was born. 4. Is there any competition out there in the market? Currently we don't have any competitors that share the same cause. What makes our platform different is the ideology that our product promotes and the functionalities that our platform offers for easy socialization based on interests and knowledge sharing. 5. What are the main technologies used to build Emit Knowledge? Emit Knowledge was built on a heterogeneous pallet of technologies. Currently, we have four of separation: UI – Built on ASP.NET MVC3 and Knockout.js; Messaging infrastructure – Build on top of RabbitMQ; Background services – Our in-house solution for job distribution, orchestration and processing; Data storage – Build on top of MongoDB; What are the main reasons you've chosen ASP.NET MVC? Since all of our team members are .NET engineers, the decision was very natural. ASP.NET MVC is the only Microsoft web stack that sticks to the HTTP behavioral standards. It is easy to work with, have a tiny learning curve and everyone who is familiar with the HTTP will understand its architecture and convention without any difficulties. 6. What are the main reasons for choosing ASP.NET MVC? Since all of our team members are .NET engineers, the decision was very natural. ASP.NET MVC is the only Microsoft web stack that sticks to the HTTP behavioral standards. It is easy to work with, have a tiny learning curve and everyone who is familiar with the HTTP will understand its architecture and convention without any difficulties. 7. Did you use some of the latest Microsoft technologies? If yes, which ones? Yes, we like to rock the cutting edge tech house. Currently we are using Microsoft’s latest technologies like ASP.NET MVC, Web API (work in progress) and the best for the last; we are utilizing Windows Azure IaaS to the bone. 8. Can you please tell us shortly, what would be the benefit of regular bloggers in other blogging platforms to join Emit Knowledge? Well, unless you are some of the smoking ace gurus whose blogs are followed by a large number of users, our platform offers knowledge based segregated community equipped with tools that will enable both current and future users to expand their relations and to self-promote in the community based on their activity and knowledge sharing. 10. I see you are working very intensively and there is already integration with some third-party services to make the process of sharing and emitting knowledge easier, which services did you integrate until now and what do you plan do to next? We have “reemit” functionality for internal sharing and we also support external services like: Twitter; LinkedIn; Facebook; For the regular bloggers we have an extra cream, Windows Live Writer support for easy blog posts emitting. 11. What should we expect next? Currently, we are working on a new fancy community feature. This means that we are going to support user groups to be formed. So for all existing communities and user groups out there, wait us a little bit, we are coming for rescue :). One of the top next features they are developing is the Community Feature. It means, if you have your own User Group, Community Group or any other Group on which you and your users are mostly blogging or sharing (emitting) knowledge in various ways, Emit Knowledge as a platform will help you have everything you need to promote your group, make new followers and host all the necessary stuff that you have had need of. I would invite you to try the network and start sharing knowledge in a way that will help you gather new followers and spread your knowledge faster, easier and in a more efficient way! Let’s Emit Knowledge!

    Read the article

  • Reflect.Emit Dynamic Type Memory Blowup

    - by Firestrand
    Using C# 3.5 I am trying to generate dynamic types at runtime using reflection emit. I used the Dynamic Query Library sample from Microsoft to create a class generator. Everything works, my problem is that 100 generated types inflate the memory usage by approximately 25MB. This is a completely unacceptable memory profile as eventually I want to support having several hundred thousand types generated in memory. Memory profiling shows that the memory is apparently being held by various System.Reflection.Emit types and methods though I can't figure out why. I haven't found others talking about this problem so I am hoping someone in this community either knows what I am doing wrong or if this is expected behavior. Contrived Example below: using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Reflection.Emit; namespace SmallRelfectExample { class Program { static void Main(string[] args) { int typeCount = 100; int propCount = 100; Random rand = new Random(); Type dynType = null; for (int i = 0; i < typeCount; i++) { List<DynamicProperty> dpl = new List<DynamicProperty>(propCount); for (int j = 0; j < propCount; j++) { dpl.Add(new DynamicProperty("Key" + rand.Next().ToString(), typeof(String))); } SlimClassFactory scf = new SlimClassFactory(); dynType = scf.CreateDynamicClass(dpl.ToArray(), i); //Optionally do something with the type here } Console.WriteLine("SmallRelfectExample: {0} Types generated.", typeCount); Console.ReadLine(); } } public class SlimClassFactory { private readonly ModuleBuilder module; public SlimClassFactory() { AssemblyName name = new AssemblyName("DynamicClasses"); AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); module = assembly.DefineDynamicModule("Module"); } public Type CreateDynamicClass(DynamicProperty[] properties, int Id) { string typeName = "DynamicClass" + Id.ToString(); TypeBuilder tb = module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(DynamicClass)); FieldInfo[] fields = GenerateProperties(tb, properties); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); return result; } static FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties) { FieldInfo[] fields = new FieldBuilder[properties.Length]; for (int i = 0; i < properties.Length; i++) { DynamicProperty dp = properties[i]; FieldBuilder fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private); PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null); MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, dp.Type, Type.EmptyTypes); ILGenerator genGet = mbGet.GetILGenerator(); genGet.Emit(OpCodes.Ldarg_0); genGet.Emit(OpCodes.Ldfld, fb); genGet.Emit(OpCodes.Ret); MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new Type[] { dp.Type }); ILGenerator genSet = mbSet.GetILGenerator(); genSet.Emit(OpCodes.Ldarg_0); genSet.Emit(OpCodes.Ldarg_1); genSet.Emit(OpCodes.Stfld, fb); genSet.Emit(OpCodes.Ret); pb.SetGetMethod(mbGet); pb.SetSetMethod(mbSet); fields[i] = fb; } return fields; } static void GenerateEquals(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(bool), new Type[] { typeof(object) }); ILGenerator gen = mb.GetILGenerator(); LocalBuilder other = gen.DeclareLocal(tb); Label next = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Isinst, tb); gen.Emit(OpCodes.Stloc, other); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); next = gen.DefineLabel(); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new Type[] { ft, ft }), null); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); } gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Ret); } static void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(int), Type.EmptyTypes); ILGenerator gen = mb.GetILGenerator(); gen.Emit(OpCodes.Ldc_I4_0); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new Type[] { ft }), null); gen.Emit(OpCodes.Xor); } gen.Emit(OpCodes.Ret); } } public abstract class DynamicClass { public override string ToString() { PropertyInfo[] props = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); StringBuilder sb = new StringBuilder(); sb.Append("{"); for (int i = 0; i < props.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(props[i].Name); sb.Append("="); sb.Append(props[i].GetValue(this, null)); } sb.Append("}"); return sb.ToString(); } } public class DynamicProperty { private readonly string name; private readonly Type type; public DynamicProperty(string name, Type type) { if (name == null) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); this.name = name; this.type = type; } public string Name { get { return name; } } public Type Type { get { return type; } } } }

    Read the article

  • Reflection: Is using reflection still "bad" or "slow"? What has changed with reflection since 2002?

    - by blesh
    I've noticed when dealing with Expressions or Expression Trees I'm using reflection a lot to set and get values in properties and what have you. It has occurred to me that the use of reflection seems to be getting more and more common. Things like DataAnotations for validation, Attribute heavy ORMs, etc. Have me wondering: What has changed since the days years and years ago when I used to be told to avoid reflection if at all possible? So what, if anything has changed? Is it just the speed of the machines? Have there been changes to the framework to speed up reflection? Or has nothing really changed? Is it still "bad" or "slow" to use reflection? EDIT: To clarify my question a little.

    Read the article

  • Trouble Emitting Object Array using Reflection.Emit

    - by JoeGeeky
    I am trying to Emit what I thought would be a simple object array that would result in code similar to the below example object[] parameters = new object[] { a, b, }; When I write the above code in C# using VS, I get the following IL. As expected this works. .locals init ( [0] object[] parameters, [1] object[] CS$0$0000) However, when I try and Emit IL directly, I only ever get a one index init array. Can someone help tell me where I've gone wrong here? Here is the Emit code I'm using: int arraySize = 2; LocalBuilder paramValues = ilGenerator.DeclareLocal(typeof(object[])); paramValues.SetLocalSymInfo("parameters"); ilGenerator.Emit(OpCodes.Ldc_I4_S, arraySize); ilGenerator.Emit(OpCodes.Newarr, typeof(object)); ilGenerator.Emit(OpCodes.Stloc, paramValues); Here is the resulting IL: .locals init ( [0] object[] objArray) The rest of the resulting IL is identical between the two solutions, but for some reason the .locals init is different.

    Read the article

  • Saving Types generated via Reflection.Emit as code file (.cs) instead of saving it in .dll files

    - by Manish Sinha
    Before start let me tell my experience: I am experienced with C#.NET, web services, XML part and few more. Reflection is something new to me, though I have read extensively on it and tried out some experimental code, but haven't made anything great using reflection I checked out many examples of how we can create Type at runtime and then which can be saved in an assembly (.dll) files. Of all the examples I have seen is about saving the created types in the .dll files instead of code file. Isn't there any way to create the code file out of reflection? I need to create code file since I want to distribute code instead of compiled assemblies. What I want to do is something like xsd.exe does, either spit out a .dll or the code file(in any language). Isn't there any way to create a code file, since most of the place I can find is AssemblyBuilder ab = System.AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save); and then lastly ab.Save("QuoteOfTheDay.dll");

    Read the article

  • Why isn't reflection on the SCJP / OCJP?

    - by Nick Rosencrantz
    I read through Kathy Sierra's SCJP study guide and I will read it again more throughly to improve myself as a Java programmer and be able to take the certification either Java 6 or wait for the Java 7 exam (I'm already employed as Java developer so I'm in no hurry to take the exam.) Now I wonder why reflection is not on the exam? The book it seems covers everything that should be on the exam and AFAIK reflection is at least as important as threads if not more used inpractice since many frameworks use reflection. Do you know why reflection is not part of the SCJP? Do you agree that it's at least important to know reflection as threads? Thanks for any answer

    Read the article

  • Real world uses of Reflection.Emit

    - by Ryu
    In all the books I've read on reflection they often say that there aren't many cases where you want to generate IL on the fly, but they don't give any examples of where it does make sense. After seeing Reflection.Emit as a job requirement for a gaming company I was curious where else it's being used. I'm now wondering if there are any situations you've seen in the real world were it was the best solution to the problem. Perhaps it is used as an implementation to a design pattern? Note I imagine PostSharp / AOP uses it.

    Read the article

  • Creating DescriptionAttribute on Enumeration Field using System.Reflection.Emit

    - by Manish Sinha
    I have a list of strings which are candidates for Enumerations values. They are Don't send diffs 500 lines 1000 lines 5000 lines Send entire diff The problem is that spaces, special characters are not a part of identifiers and even cannot start with a number, so I would be sanitizing these values to only chars, numbers and _ To keep the original values I thought of putting these strings in the DescriptionAttribute, such that the final Enum should look like public enum DiffBehvaiour { [Description("Don't send diffs")] Dont_send_diffs, [Description("500 lines")] Diff_500_lines, [Description("1000 lines")] Diff_1000_lines, [Description("5000 lines")] Diff_5000_lines, [Description("Send entire diff")] Send_entire_diff } Then later using code I will retrieve the real string associated with the enumeration value, so that the correct string can be sent back the web service to get the correct resource. I want to know how to create the DescriptionAttribute using System.Reflection.Emit Basically the question is where and how to store the original string so that when the Enumeration value is chosen, the corresponding value can be retrieved. I am also interested in knowing how to access DescriptionAttribute when needed.

    Read the article

  • Using runtime generic type reflection to build a smarter DAO

    - by kerry
    Have you ever wished you could get the runtime type of your generic class? I wonder why they didn’t put this in the language. It is possible, however, with reflection: Consider a data access object (DAO) (note: I had to use brackets b/c the arrows were messing with wordpress): public interface Identifiable { public Long getId(); } public interface Dao { public T findById(Long id); public void save(T obj); public void delete(T obj); } Using reflection, we can create a DAO implementation base class, HibernateDao, that will work for any object: import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; public class HibernateDao implements Dao { private final Class clazz; public HibernateDao(Session session) { // the magic ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass(); return (Class) parameterizedType.getActualTypeArguments()[0]; } public T findById(Long id) { return session.get(clazz, id); } public void save(T obj) { session.saveOrUpdate(obj); } public void delete(T obj) { session.delete(obj); } } Then, all we have to do is extend from the class: public class BookDaoHibernateImpl extends HibernateDao { }

    Read the article

  • XNA Moddable Game - Architecture Design and Reflection

    - by David K
    I've decided to embark on an XNA moddable game project of a simple rogue style. For all purposes of this question, I'm going to not be using a scripting engine, but rather allow modders to directly compile assemblies that are loaded by the game at run time. I know about the security problems this may raise. So in order to expose the moddable content, I have gone about creating a generic project in XNA called MyModel. This contains a number of interfaces that all inherit from IPlugin, such as IGameSystem, IRenderingSystem, IHud, IInputSystem etc. Then I've created another project called MyRogueModel. This references MyModel project, and holds interfaces such as IMonster, IPlayer, IDungeonGenerator, IInventorySystem. More rogue specific interfaces, but again, all interfaces in this project inherit from IPlugin. Then finally, I've created another project called MyRogueGame, that references both MyModel and MyRogueModel projects. This project will be the game that you run and play. Here I have put the actual implementation of the Monster, DungeonGenerator, InputSystem and RenderingSystem classes. This project will also scan the mods directory during run time and load any IPlugins it finds using reflection and override anything it finds from the default. For example if it finds a new implementation of the DungeonGenerator it will use that one instead. Now my question is, in order to get this far, I have effectively 2 projects that contain nothing but interfaces... which seems a little... strange ? For people to create mods for the game, I would give them both the MyModel and MyRogueModel assemblies in which they would reference. I'm not sure whether this is the right way to do it, but my reasoning goes as follows : If I write 1 input system, I can use it in any game I write. If I create 3 rogue like games, and a modder writes 1 rendering system, that modder could use the rendering system for all 3 games, because it all comes from the MyModel project. I come from a more web based C# role, so having empty interface projects doesn't seem wrong, its just something I haven't done before. Before I embark on something that might be crazy, I'd just like to know whether this is a foolish idea and whether there's a better (or established) design principle I should be following ?

    Read the article

  • C++ property system interface for game editors (reflection system)

    - by Cristopher Ismael Sosa Abarca
    I have designed an reusable game engine for an project, and their functionality is like this: Is a completely scripted game engine instead of the usual scripting languages as Lua or Python, this uses Runtime-Compiled C++, and an modified version of Cistron (an component-based programming framework).to be compatible with Runtime-Compiled C++ and so on. Using the typical GameObject and Component classes of the Component-based design pattern, is serializable via JSON, BSON or Binary useful for selecting which objects will be loaded the next time. The main problem: We want to use our custom GameObjects and their components properties in our level editor, before used hardcoded functions to access GameObject base class virtual functions from the derived ones, if do you want to modify an property specifically from that class you need inside into the code, this situation happens too with the derived classes of Component class, in little projects there's no problem but for larger projects becomes tedious, lengthy and error-prone. I've researched a lot to find a solution without luck, i tried with the Ogitor's property system (since our engine is Ogre-based) but we find it inappropiate for the component-based design and it's limited only for the Ogre classes and can lead to performance overhead, and we tried some code we find in the Internet we tested it and worked a little but we considered the macro and lambda abuse too horrible take a look (some code omitted): IWE_IMPLEMENT_PROP_BEGIN(CBaseEntity) IWE_PROP_LEVEL_BEGIN("Editor"); IWE_PROP_INT_S("Id", "Internal id", m_nEntID, [](int n) {}, true); IWE_PROP_LEVEL_END(); IWE_PROP_LEVEL_BEGIN("Entity"); IWE_PROP_STRING_S("Mesh", "Mesh used for this entity", m_pModelName, [pInst](const std::string& sModelName) { pInst->m_stackMemUndoType.push(ENT_MEM_MESH); pInst->m_stackMemUndoStr.push(pInst->getModelName()); pInst->setModel(sModelName, false); pInst->saveState(); }, false); IWE_PROP_VECTOR3_S("Position", m_vecPosition, [pInst](float fX, float fY, float fZ) { pInst->m_stackMemUndoType.push(ENT_MEM_POSITION); pInst->m_stackMemUndoVec3.push(pInst->getPosition()); pInst->saveState(); pInst->m_vecPosition.Get()[0] = fX; pInst->m_vecPosition.Get()[1] = fY; pInst->m_vecPosition.Get()[2] = fZ; pInst->setPosition(pInst->m_vecPosition); }, false); IWE_PROP_QUATERNION_S("Orientation (Quat)", m_quatOrientation, [pInst](float fW, float fX, float fY, float fZ) { pInst->m_stackMemUndoType.push(ENT_MEM_ROTATE); pInst->m_stackMemUndoQuat.push(pInst->getOrientation()); pInst->saveState(); pInst->m_quatOrientation.Get()[0] = fW; pInst->m_quatOrientation.Get()[1] = fX; pInst->m_quatOrientation.Get()[2] = fY; pInst->m_quatOrientation.Get()[3] = fZ; pInst->setOrientation(pInst->m_quatOrientation); }, false); IWE_PROP_LEVEL_END(); IWE_IMPLEMENT_PROP_END() We are finding an simplified way to this, without leading confusing the programmers, (will be released to the public) i find ways to achieve this but they are only available for the common scripting as Lua or editors using C#. also too portable, we can write "wrappers" for different GUI toolkits as Qt or GTK, also i'm thinking to using Boost.Wave to get additional macro functionality without creating my own compiler. The properties designed to use in the editor they are removed in the game since the save file contains their data and loads it using an simple 'load' function to reduce unnecessary code bloat may will be useful if some GameObject property wants to be hidden instead. In summary, there's a way to implement an reflection(property) system for a level editor based in properties from derived classes? Also we can use C++11 and Boost (restricted only to Wave and PropertyTree)

    Read the article

  • Problems with generation of dynamic code

    - by user308344
    This code gif an exception: Invocation exception, please help, I don't know what happen, I think is some thing with the Add because he work when I push onto the stack intergers, and when i push lvalue It's didn't work, thanks static void Main(string[] args) { AppDomain dominioAplicacion = System.Threading.Thread.GetDomain(); AssemblyName nombre_Del_Ensamblado = new AssemblyName("ASS"); AssemblyBuilder ensambladoBld = dominioAplicacion.DefineDynamicAssembly(nombre_Del_Ensamblado, AssemblyBuilderAccess.RunAndSave); ModuleBuilder moduloBld = ensambladoBld.DefineDynamicModule("<MOD"); TypeBuilder claseContenedoraBld = moduloBld.DefineType("claseContenedora"); MethodBuilder mainBld = claseContenedoraBld.DefineMethod("main", MethodAttributes.Public | MethodAttributes.Static, typeof(void), Type.EmptyTypes); ILGenerator il = mainBld.GetILGenerator(); FieldBuilder campoBld = claseContenedoraBld.DefineField("x", typeof(int), FieldAttributes.Public | FieldAttributes.Static); il.Emit(OpCodes.Ldc_I4, 2); il.Emit(OpCodes.Stsfld, campoBld); FieldBuilder campoBld1 = claseContenedoraBld.DefineField("x1", typeof(int), FieldAttributes.Public | FieldAttributes.Static); il.Emit(OpCodes.Ldc_I4, 2); il.Emit(OpCodes.Stsfld, campoBld1); il.Emit(OpCodes.Ldftn, campoBld); //il.Emit(OpCodes.Unbox, typeof(int)); //il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldftn, campoBld1); //il.Emit(OpCodes.Unbox, typeof(int)); il.Emit(OpCodes.Stloc_1); il.Emit(OpCodes.Ldloc_1); //il.Emit(OpCodes.Box, typeof(int)); //il.Emit(OpCodes.Ldftn, campoBld1); //il.Emit(OpCodes.Unbox, typeof(int)); il.Emit(OpCodes.Add); il.Emit(OpCodes.Pop); //il.Emit(OpCodes.Stsfld, campoBld1); il.Emit(OpCodes.Ret); Type t = claseContenedoraBld.CreateType(); object ptInstance = Activator.CreateInstance(t, new Type[] { }); t.InvokeMember("main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, ptInstance, new object[0]); var x = t.GetField("x"); }

    Read the article

  • System.Reflection - Global methods aren't available for reflection

    - by mrjoltcola
    I have an issue with a semantic gap between the CLR and System.Reflection. System.Reflection does not (AFAIK) support reflecting on global methods in an assembly. At the assembly level, I must start with the root types. My compiler can produce assemblies with global methods, and my standard bootstrap lib is a dll that includes some global methods. My compiler uses System.Reflection to import assembly metadata at compile time. It seems if I depend on System.Reflection, global methods are not a possibility. The cleanest solution is to convert all of my standard methods to class static methods, but the point is, my language allows global methods, and the CLR supports it, but System.Reflection leaves a gap. ildasm shows the global methods just fine, but I assume it does not use System.Reflection itself and goes right to the metadata and bytecode. Besides System.Reflection, is anyone aware of any other 3rd party reflection or disassembly libs that I could make use of (assuming I will eventually release my compiler as free, BSD licensed open source).

    Read the article

  • Java: Reflection Packet Builder using getField()

    - by Matchlighter
    So I just finished writing a packet builder that dynamically loads data into a data stream which is then sent out. Each builder operates by finding fields in its class (and its superclasses) that are marked with an @data annotation. Upon finishing the builder, I remembered that getFields() does not return in "any specific order". I quite like my builder because it allows for quite simple, yet hard-typed packets. Could this implementation be a problem? What would be the best next step to keep the simplicity - do alphabetical sorting of fields?

    Read the article

  • How to make room reflection using Cubemap

    - by MaT
    I am trying to use a cube map of the inside of a room to create some reflections on walls, ceiling and floor. But when I use the cube map, the reflected image is not correct. The point of view seems to be false. To be correct I use a different cube map for each walls, floor or ceiling. The cube map is calculated from the center of the plane looking at the room. Are there specialized techniques to achieve such effect ? Thanks a lot !

    Read the article

  • Reflection velocity

    - by MindSeeker
    I'm trying to get a moving circular object to bounce (elastically) off of an immovable circular object. Am I doing this right? (The results look right, but I hate to trust that alone, and I can't find a tutorial that tackles this problem and includes the nitty gritty math/code to verify what I'm doing). If it is right, is there a better/faster/more elegant way to do this? Note that the object (this) is the moving circle, and the EntPointer object is the immovable circle. //take vector separating the two centers <x, y>, and then get unit vector of the result: MathVector2d unitnormal = MathVector2d(this -> Retxpos() - EntPointer -> Retxpos(), this -> Retypos() - EntPointer -> Retypos()).UnitVector(); //take tangent <-y, x> of the unitnormal: MathVector2d unittangent = MathVector2d(-unitnormal.ycomp, unitnormal.xcomp); MathVector2d V1 = MathVector2d(this -> Retxvel(), this -> Retyvel()); //Calculate the normal and tangent vector lengths of the velocity: (the normal changes, the tangent stays the same) double LengthNormal = DotProduct(unitnormal, V1); double LengthTangent = DotProduct(unittangent, V1); MathVector2d VelVecNewNormal = unitnormal.ScalarMultiplication(-LengthNormal); //the negative of what it was before MathVector2d VelVecNewTangent = unittangent.ScalarMultiplication(LengthTangent); //this stays the same MathVector2d NewVel = VectorAddition(VelVecNewNormal, VelVecNewTangent); //combine them xvel = NewVel.xcomp; //and then apply them yvel = NewVel.ycomp; Note also that this question is just about velocity, the position code is handled elsewhere (in other words, assume that this code is implemented at the exact moment that the circles begin to overlap). Thanks in advance for your help and time!

    Read the article

  • Using Reflection.Emit to emit a "using (x) { ... }" block?

    - by Lasse V. Karlsen
    I'm trying to use Reflection.Emit in C# to emit a using (x) { ... } block. At the point I am in code, I need to take the current top of the stack, which is an object that implements IDisposable, store this away in a local variable, implement a using block on that variable, and then inside it add some more code (I can deal with that last part.) Here's a sample C# piece of code I tried to compile and look at in Reflector: public void Test() { TestDisposable disposable = new TestDisposable(); using (disposable) { throw new Exception("Test"); } } This looks like this in Reflector: .method public hidebysig instance void Test() cil managed { .maxstack 2 .locals init ( [0] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable disposable, [1] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable CS$3$0000, [2] bool CS$4$0001) L_0000: nop L_0001: newobj instance void LVK.Reflection.Tests.UsingConstructTests/TestDisposable::.ctor() L_0006: stloc.0 L_0007: ldloc.0 L_0008: stloc.1 L_0009: nop L_000a: ldstr "Test" L_000f: newobj instance void [mscorlib]System.Exception::.ctor(string) L_0014: throw L_0015: ldloc.1 L_0016: ldnull L_0017: ceq L_0019: stloc.2 L_001a: ldloc.2 L_001b: brtrue.s L_0024 L_001d: ldloc.1 L_001e: callvirt instance void [mscorlib]System.IDisposable::Dispose() L_0023: nop L_0024: endfinally .try L_0009 to L_0015 finally handler L_0015 to L_0025 } I have no idea how to deal with that ".try ..." part at the end there when using Reflection.Emit. Can someone point me in the right direction?

    Read the article

  • Replacing instructions in a method's MethodBody

    - by Alix
    Hi, (First of all, this is a very lengthy post, but don't worry: I've already implemented all of it, I'm just asking your opinion.) I'm having trouble implementing the following; I'd appreciate some help: I get a Type as parameter. I define a subclass using reflection. Notice that I don't intend to modify the original type, but create a new one. I create a property per field of the original class, like so: public class OriginalClass { private int x; } public class Subclass : OriginalClass { private int x; public int X { get { return x; } set { x = value; } } } For every method of the superclass, I create an analogous method in the subclass. The method's body must be the same except that I replace the instructions ldfld x with callvirt this.get_X, that is, instead of reading from the field directly I call the get accessor. I'm having trouble with step 4. I know you're not supposed to manipulate code like this, but I really need to. Here's what I've tried: Attempt #1: Use Mono.Cecil. This would allow me to parse the body of the method into human-readable Instructions, and easily replace instructions. However, the original type isn't in a .dll file, so I can't find a way to load it with Mono.Cecil. Writing the type to a .dll, then load it, then modify it and write the new type to disk (which I think is the way you create a type with Mono.Cecil), and then load it seems like a huge overhead. Attempt #2: Use Mono.Reflection. This would also allow me to parse the body into Instructions, but then I have no support for replacing instructions. I've implemented a very ugly and inefficient solution using Mono.Reflection, but it doesn't yet support methods that contain try-catch statements (although I guess I can implement this) and I'm concerned that there may be other scenarios in which it won't work, since I'm using the ILGenerator in a somewhat unusual way. Also, it's very ugly ;). Here's what I've done: private void TransformMethod(MethodInfo methodInfo) { // Create a method with the same signature. ParameterInfo[] paramList = methodInfo.GetParameters(); Type[] args = new Type[paramList.Length]; for (int i = 0; i < args.Length; i++) { args[i] = paramList[i].ParameterType; } MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args); ILGenerator ilGen = methodBuilder.GetILGenerator(); // Declare the same local variables as in the original method. IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables; foreach (LocalVariableInfo local in locals) { ilGen.DeclareLocal(local.LocalType); } // Get readable instructions. IList<Instruction> instructions = methodInfo.GetInstructions(); // I first need to define labels for every instruction in case I // later find a jump to that instruction. Once the instruction has // been emitted I cannot label it, so I'll need to do it in advance. // Since I'm doing a first pass on the method's body anyway, I could // instead just create labels where they are truly needed, but for // now I'm using this quick fix. Dictionary<int, Label> labels = new Dictionary<int, Label>(); foreach (Instruction instr in instructions) { labels[instr.Offset] = ilGen.DefineLabel(); } foreach (Instruction instr in instructions) { // Mark this instruction with a label, in case there's a branch // instruction that jumps here. ilGen.MarkLabel(labels[instr.Offset]); // If this is the instruction that I want to replace (ldfld x)... if (instr.OpCode == OpCodes.Ldfld) { // ...get the get accessor for the accessed field (get_X()) // (I have the accessors in a dictionary; this isn't relevant), MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0]; // ...instead of emitting the original instruction (ldfld x), // emit a call to the get accessor, ilGen.Emit(OpCodes.Callvirt, safeReadAccessor); // Else (it's any other instruction), reemit the instruction, unaltered. } else { Reemit(instr, ilGen, labels); } } } And here comes the horrible, horrible Reemit method: private void Reemit(Instruction instr, ILGenerator ilGen, Dictionary<int, Label> labels) { // If the instruction doesn't have an operand, emit the opcode and return. if (instr.Operand == null) { ilGen.Emit(instr.OpCode); return; } // Else (it has an operand)... // If it's a branch instruction, retrieve the corresponding label (to // which we want to jump), emit the instruction and return. if (instr.OpCode.FlowControl == FlowControl.Branch) { ilGen.Emit(instr.OpCode, labels[Int32.Parse(instr.Operand.ToString())]); return; } // Otherwise, simply emit the instruction. I need to use the right // Emit call, so I need to cast the operand to its type. Type operandType = instr.Operand.GetType(); if (typeof(byte).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (byte) instr.Operand); else if (typeof(double).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (double) instr.Operand); else if (typeof(float).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (float) instr.Operand); else if (typeof(int).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (int) instr.Operand); ... // you get the idea. This is a pretty long method, all like this. } Branch instructions are a special case because instr.Operand is SByte, but Emit expects an operand of type Label. Hence the need for the Dictionary labels. As you can see, this is pretty horrible. What's more, it doesn't work in all cases, for instance with methods that contain try-catch statements, since I haven't emitted them using methods BeginExceptionBlock, BeginCatchBlock, etc, of ILGenerator. This is getting complicated. I guess I can do it: MethodBody has a list of ExceptionHandlingClause that should contain the necessary information to do this. But I don't like this solution anyway, so I'll save this as a last-resort solution. Attempt #3: Go bare-back and just copy the byte array returned by MethodBody.GetILAsByteArray(), since I only want to replace a single instruction for another single instruction of the same size that produces the exact same result: it loads the same type of object on the stack, etc. So there won't be any labels shifting and everything should work exactly the same. I've done this, replacing specific bytes of the array and then calling MethodBuilder.CreateMethodBody(byte[], int), but I still get the same error with exceptions, and I still need to declare the local variables or I'll get an error... even when I simply copy the method's body and don't change anything. So this is more efficient but I still have to take care of the exceptions, etc. Sigh. Here's the implementation of attempt #3, in case anyone is interested: private void TransformMethod(MethodInfo methodInfo, Dictionary<string, MethodInfo[]> dataMembersSafeAccessors, ModuleBuilder moduleBuilder) { ParameterInfo[] paramList = methodInfo.GetParameters(); Type[] args = new Type[paramList.Length]; for (int i = 0; i < args.Length; i++) { args[i] = paramList[i].ParameterType; } MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args); ILGenerator ilGen = methodBuilder.GetILGenerator(); IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables; foreach (LocalVariableInfo local in locals) { ilGen.DeclareLocal(local.LocalType); } byte[] rawInstructions = methodInfo.GetMethodBody().GetILAsByteArray(); IList<Instruction> instructions = methodInfo.GetInstructions(); int k = 0; foreach (Instruction instr in instructions) { if (instr.OpCode == OpCodes.Ldfld) { MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0]; // Copy the opcode: Callvirt. byte[] bytes = toByteArray(OpCodes.Callvirt.Value); for (int m = 0; m < OpCodes.Callvirt.Size; m++) { rawInstructions[k++] = bytes[put.Length - 1 - m]; } // Copy the operand: the accessor's metadata token. bytes = toByteArray(moduleBuilder.GetMethodToken(safeReadAccessor).Token); for (int m = instr.Size - OpCodes.Ldfld.Size - 1; m >= 0; m--) { rawInstructions[k++] = bytes[m]; } // Skip this instruction (do not replace it). } else { k += instr.Size; } } methodBuilder.CreateMethodBody(rawInstructions, rawInstructions.Length); } private static byte[] toByteArray(int intValue) { byte[] intBytes = BitConverter.GetBytes(intValue); if (BitConverter.IsLittleEndian) Array.Reverse(intBytes); return intBytes; } private static byte[] toByteArray(short shortValue) { byte[] intBytes = BitConverter.GetBytes(shortValue); if (BitConverter.IsLittleEndian) Array.Reverse(intBytes); return intBytes; } (I know it isn't pretty. Sorry. I put it quickly together to see if it would work.) I don't have much hope, but can anyone suggest anything better than this? Sorry about the extremely lengthy post, and thanks.

    Read the article

  • Inserting instructions into method.

    - by Alix
    Hi, (First of all, this is a very lengthy post, but don't worry: I've already implemented all of it, I'm just asking your opinion.) I'm having trouble implementing the following; I'd appreciate some help: I get a Type as parameter. I define a subclass using reflection. Notice that I don't intend to modify the original type, but create a new one. I create a property per field of the original class, like so: [- ignore this text here; I had to add something or the formatting wouldn't work <-] public class OriginalClass { private int x; } public class Subclass : OriginalClass { private int x; public int X { get { return x; } set { x = value; } } } [This is number 4! Numbered lists don't work if you add code in between; sorry] For every method of the superclass, I create an analogous method in the subclass. The method's body must be the same except that I replace the instructions ldfld x with callvirt this.get_X, that is, instead of reading from the field directly I call the get accessor. I'm having trouble with step 4. I know you're not supposed to manipulate code like this, but I really need to. Here's what I've tried: Attempt #1: Use Mono.Cecil. This would allow me to parse the body of the method into human-readable Instructions, and easily replace instructions. However, the original type isn't in a .dll file, so I can't find a way to load it with Mono.Cecil. Writing the type to a .dll, then load it, then modify it and write the new type to disk (which I think is the way you create a type with Mono.Cecil), and then load it seems like a huge overhead. Attempt #2: Use Mono.Reflection. This would also allow me to parse the body into Instructions, but then I have no support for replacing instructions. I've implemented a very ugly and inefficient solution using Mono.Reflection, but it doesn't yet support methods that contain try-catch statements (although I guess I can implement this) and I'm concerned that there may be other scenarios in which it won't work, since I'm using the ILGenerator in a somewhat unusual way. Also, it's very ugly ;). Here's what I've done: private void TransformMethod(MethodInfo methodInfo) { // Create a method with the same signature. ParameterInfo[] paramList = methodInfo.GetParameters(); Type[] args = new Type[paramList.Length]; for (int i = 0; i < args.Length; i++) { args[i] = paramList[i].ParameterType; } MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args); ILGenerator ilGen = methodBuilder.GetILGenerator(); // Declare the same local variables as in the original method. IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables; foreach (LocalVariableInfo local in locals) { ilGen.DeclareLocal(local.LocalType); } // Get readable instructions. IList<Instruction> instructions = methodInfo.GetInstructions(); // I first need to define labels for every instruction in case I // later find a jump to that instruction. Once the instruction has // been emitted I cannot label it, so I'll need to do it in advance. // Since I'm doing a first pass on the method's body anyway, I could // instead just create labels where they are truly needed, but for // now I'm using this quick fix. Dictionary<int, Label> labels = new Dictionary<int, Label>(); foreach (Instruction instr in instructions) { labels[instr.Offset] = ilGen.DefineLabel(); } foreach (Instruction instr in instructions) { // Mark this instruction with a label, in case there's a branch // instruction that jumps here. ilGen.MarkLabel(labels[instr.Offset]); // If this is the instruction that I want to replace (ldfld x)... if (instr.OpCode == OpCodes.Ldfld) { // ...get the get accessor for the accessed field (get_X()) // (I have the accessors in a dictionary; this isn't relevant), MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0]; // ...instead of emitting the original instruction (ldfld x), // emit a call to the get accessor, ilGen.Emit(OpCodes.Callvirt, safeReadAccessor); // Else (it's any other instruction), reemit the instruction, unaltered. } else { Reemit(instr, ilGen, labels); } } } And here comes the horrible, horrible Reemit method: private void Reemit(Instruction instr, ILGenerator ilGen, Dictionary<int, Label> labels) { // If the instruction doesn't have an operand, emit the opcode and return. if (instr.Operand == null) { ilGen.Emit(instr.OpCode); return; } // Else (it has an operand)... // If it's a branch instruction, retrieve the corresponding label (to // which we want to jump), emit the instruction and return. if (instr.OpCode.FlowControl == FlowControl.Branch) { ilGen.Emit(instr.OpCode, labels[Int32.Parse(instr.Operand.ToString())]); return; } // Otherwise, simply emit the instruction. I need to use the right // Emit call, so I need to cast the operand to its type. Type operandType = instr.Operand.GetType(); if (typeof(byte).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (byte) instr.Operand); else if (typeof(double).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (double) instr.Operand); else if (typeof(float).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (float) instr.Operand); else if (typeof(int).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (int) instr.Operand); ... // you get the idea. This is a pretty long method, all like this. } Branch instructions are a special case because instr.Operand is SByte, but Emit expects an operand of type Label. Hence the need for the Dictionary labels. As you can see, this is pretty horrible. What's more, it doesn't work in all cases, for instance with methods that contain try-catch statements, since I haven't emitted them using methods BeginExceptionBlock, BeginCatchBlock, etc, of ILGenerator. This is getting complicated. I guess I can do it: MethodBody has a list of ExceptionHandlingClause that should contain the necessary information to do this. But I don't like this solution anyway, so I'll save this as a last-resort solution. Attempt #3: Go bare-back and just copy the byte array returned by MethodBody.GetILAsByteArray(), since I only want to replace a single instruction for another single instruction of the same size that produces the exact same result: it loads the same type of object on the stack, etc. So there won't be any labels shifting and everything should work exactly the same. I've done this, replacing specific bytes of the array and then calling MethodBuilder.CreateMethodBody(byte[], int), but I still get the same error with exceptions, and I still need to declare the local variables or I'll get an error... even when I simply copy the method's body and don't change anything. So this is more efficient but I still have to take care of the exceptions, etc. Sigh. Here's the implementation of attempt #3, in case anyone is interested: private void TransformMethod(MethodInfo methodInfo, Dictionary<string, MethodInfo[]> dataMembersSafeAccessors, ModuleBuilder moduleBuilder) { ParameterInfo[] paramList = methodInfo.GetParameters(); Type[] args = new Type[paramList.Length]; for (int i = 0; i < args.Length; i++) { args[i] = paramList[i].ParameterType; } MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args); ILGenerator ilGen = methodBuilder.GetILGenerator(); IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables; foreach (LocalVariableInfo local in locals) { ilGen.DeclareLocal(local.LocalType); } byte[] rawInstructions = methodInfo.GetMethodBody().GetILAsByteArray(); IList<Instruction> instructions = methodInfo.GetInstructions(); int k = 0; foreach (Instruction instr in instructions) { if (instr.OpCode == OpCodes.Ldfld) { MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0]; byte[] bytes = toByteArray(OpCodes.Callvirt.Value); for (int m = 0; m < OpCodes.Callvirt.Size; m++) { rawInstructions[k++] = bytes[put.Length - 1 - m]; } bytes = toByteArray(moduleBuilder.GetMethodToken(safeReadAccessor).Token); for (int m = instr.Size - OpCodes.Ldfld.Size - 1; m >= 0; m--) { rawInstructions[k++] = bytes[m]; } } else { k += instr.Size; } } methodBuilder.CreateMethodBody(rawInstructions, rawInstructions.Length); } private static byte[] toByteArray(int intValue) { byte[] intBytes = BitConverter.GetBytes(intValue); if (BitConverter.IsLittleEndian) Array.Reverse(intBytes); return intBytes; } private static byte[] toByteArray(short shortValue) { byte[] intBytes = BitConverter.GetBytes(shortValue); if (BitConverter.IsLittleEndian) Array.Reverse(intBytes); return intBytes; } (I know it isn't pretty. Sorry. I put it quickly together to see if it would work.) I don't have much hope, but can anyone suggest anything better than this? Sorry about the extremely lengthy post, and thanks.

    Read the article

  • Reflection.Emit: How to convert MethodBuilder to RuntimeMethodInfo reliably?

    - by Qwertie
    After generating a type dynamically and calling TypeBuilder.CreateType, I want to create a delegate that points to a method in the new type. But if I use code like loadedType = typeBuilder.CreateType(); myDelegate = (MyDelegate)Delegate.CreateDelegate( typeof(MyDelegate), methodBuilder); Reusing the methodBuilder as a methodInfo, I get the exception "MethodInfo must be a RuntimeMethodInfo". Now normally I can re-acquire the MethodInfo with MethodInfo mi = loadedType.GetMethod(methodBuilder.Name); myDelegate = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), mi); But my class may contain several overloaded methods with the same name. How do I make sure I get the right one? Do methods have some persistent identifier I could look up in loadedType?

    Read the article

  • c#, Internal, and Reflection

    - by cyberconte
    Duplicate of: Accessing internal members via System.Reflection? Is there a way to execute "internal" code via reflection? Here is an example program: using System; using System.Reflection; namespace ReflectionInternalTest { class Program { static void Main(string[] args) { Assembly asm = Assembly.GetExecutingAssembly(); // Call normally new TestClass(); // Call with Reflection asm.CreateInstance("ReflectionInternalTest.TestClass", false, BindingFlags.Default | BindingFlags.CreateInstance, null, null, null, null); // Pause Console.ReadLine(); } } class TestClass { internal TestClass() { Console.WriteLine("Test class instantiated"); } } } Creating a testclass normally works perfectly, however when i try to create an instance via reflection, I get a missingMethodException error saying it can't find the Constructor (which is what would happen if you tried calling it from outside the assembly). Is this impossible, or is there some workaround i can do?

    Read the article

  • lambda expression based reflection vs normal reflection

    - by bitbonk
    What is the difference between normal reflection and the reflection that can be done with lambda expressions such as this (taken form build your own MVVM): public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property) { var lambda = (LambdaExpression)property; MemberExpression memberExpression; if (lambda.Body is UnaryExpression) { var unaryExpression = (UnaryExpression)lambda.Body; memberExpression = (MemberExpression)unaryExpression.Operand; } else memberExpression = (MemberExpression)lambda.Body; NotifyOfPropertyChange(memberExpression.Member.Name); } Is the lambda based reflection just using the normal reflection APIs internally? Or is this something significantly different. What is ther perfomance difference?

    Read the article

  • Using Reflection.Emit to match existing constructor

    - by yodaj007
    First, here is the C# code and the disassembled IL: public class Program<T> { private List<T> _items; public Program(T x, [Microsoft.Scripting.ParamDictionary] Microsoft.Scripting.IAttributesCollection col) { _items = new List<T>(); _items.Add(x); } } Here is the IL of that constructor: .method public hidebysig specialname rtspecialname instance void .ctor(!T x, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection col) cil managed { .param [2] .custom instance void [Microsoft.Scripting]Microsoft.Scripting.ParamDictionaryAttribute::.ctor() = ( 01 00 00 00 ) // Code size 34 (0x22) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000e: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0013: ldarg.0 IL_0014: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0019: ldarg.1 IL_001a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_001f: nop IL_0020: nop IL_0021: ret } // end of method Program`1::.ctor I am trying to understand the IL code by emitting it myself. This is what I have managed to emit: .method public hidebysig specialname rtspecialname instance void .ctor(!T A_1, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection A_2) cil managed { // Code size 34 (0x22) .maxstack 4 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000c: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0011: ldarg.0 IL_0012: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0017: ldarg.s A_1 IL_0019: nop IL_001a: nop IL_001b: nop IL_001c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_0021: ret } // end of method MyType::.ctor There are a few differences that I just can't figure out. I'm really close... How do I take care of the parameter attribute (ParamDictionaryAttribute)? I can't find a 'custom' opcode. Is the .param [2] important? How do I emit that? Why is the C# code stack size 8, while my emitted version is 4? Is this important?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >