Search Results

Search found 31989 results on 1280 pages for 'method'.

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

  • Inheriting the main method

    - by Eric
    I want to define a base class that defines a main method that instantiates the class, and runs a method. There are a couple of problems though. Here is the base class: public abstract class Strategy { abstract void execute(SoccerRobot robot); public static void main(String args) { Strategy s = new /*Not sure what to put here*/(); s.execute(new SoccerRobot()) } } And here is an example derived class: public class UselessStrategy { void execute(SoccerRobot robot) { System.out.println("I'm useless") } } It defines a simple execute method, which should be called in a main method upon usage as a the main application. However, in order to do so, I need to instantiate the derived class from within the base class's main method. Which doesn't seem to be possible. I'd rather not have to repeat the main method for every derived class, as it feels somewhat unnessary. Is there a right way of doing this?

    Read the article

  • c# passing method names as the argument in a method

    - by Alan Bennett
    hi guys, I have a recuring method which shows up many times in my code its basically checking to make sure that the connection to the odbc is ok and then connects but each time this method is called it calls another method and each instance of the main method this one is different, as each method is about 8 lines of code having it 8 times in the code isnt ideal. so basically i would like to have just one method which i can call passing the name of the new method as an arguement. so basically like: private void doSomething(methodToBeCalled) { if(somthingistrue) { methodToBeCalled(someArgument) } } is this possible? thanks in advance

    Read the article

  • Go - Concurrent method

    - by nevalu
    How to get a concurrent method? In my case, the library would be called from a program to get a value to each argument str --in method Get()--. When it's used Get() then it assigns a variable from type bytes.Buffer which it will have the value to return. The returned values --when it been concurrently called-- will be stored into a database or a file and it doesn't matter that its output been of FIFO way (from method). type test struct { foo uint8 bar uint8 } func NewTest(arg1 string) (*test, os.Error) {...} func (self *test) Get(str string) ([]byte, os.Error) { var format bytes.Buffer ... } I think that all code inner of method Get() should be put inner of go func() {...}(), and then to use a channel. Would there be a problem if it's called another method from Get()? Or would it also has to be concurrent?

    Read the article

  • [PHP] Weird problem with dynamic method invocation

    - by Rolf
    Hi everyone, this time, I'm facing a really weird problem. I've the following code: $xml = simplexml_load_file($this->interception_file); foreach($xml->children() as $class) { $path = str_replace('__CLASS_DIR__',CLASS_DIR,$class['path']); if(!is_file($path)) { throw new Exception('Bad configuration: file '.$path.' not found'); } $className = pathinfo($path,PATHINFO_FILENAME); foreach($class as $method) { $method_name = $method['name']; $obj = new $className(); var_dump(in_array($method_name,get_class_methods($className)));exit; echo $obj->$method_name();### not a method ??? } } As you can see, I get the class name and method name from an XML file. I can create an instance of the class without any problem. The var_dump at the end returns true, that means $method_name (which has 2 optional parameters) is a method of $className. BUT, and I am pretty sure the syntax is correct, when I try: $obj-$method_name() I get: Fatal error: Method name must be a string If you have any ideas, pleaaaaase tell me :) Thanks in advance, Rolf

    Read the article

  • When using method chaining, do I reuse the object or create one?

    - by MainMa
    When using method chaining like: var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create(); there may be two approaches: Reuse the same object, like this: public Car PaintedIn(Color color) { this.Color = color; return this; } Create a new object of type Car at every step, like this: public Car PaintedIn(Color color) { var car = new Car(this); // Clone the current object. car.Color = color; // Assign the values to the clone, not the original object. return car; } Is the first one wrong or it's rather a personal choice of the developer? I believe that he first approach may quickly cause the intuitive/misleading code. Example: // Create a car with neither color, nor model. var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor); // Create several cars based on the neutral car. var yellowCar = mercedes.PaintedIn(Color.Yellow).Create(); var specificModel = mercedes.OfModel(99).Create(); // Would `specificModel` car be yellow or of neutral color? How would you guess that if // `yellowCar` were in a separate method called somewhere else in code? Any thoughts?

    Read the article

  • in python: can i pass class method as and a default argument to another class method

    - by alex
    i want to to pass class method as and a default argument to another class method, so that i can re-use the method as a @classmethod @classmethod class foo: def func1(self,x): do somthing; def func2(self, aFunc = self.func1): # make some a call to afunc afunc(4) this why when the method func2 is called within the class aFunc defaults to self.func1, but i can call this same function from outside of the class and pass it a different function at the input. i get NameError: name 'self' is not defined

    Read the article

  • How to name a static factory method in the utility class?

    - by leventov
    I have an interface MyLongNameInterface with a counterpart utility class MyLongNameInterfaces. What is the best name for a static factory method in the utility class, which creates an instance of MyLongNameInterface? MyLongNameInterfaces.newInstance() -- a new instance of the utility class? MyLongNameInterfaces.newMyLongNameInterface() -- too verbose MyLongNameInterfaces.create() -- create an instance of the utility class? Also, create is not a widely used conventional verb in Java better option?

    Read the article

  • call a class method from inside an instance method from a module mixin (rails)

    - by sean
    Curious how one would go about calling a class method from inside an instance method of a module which is included by an active record class. For example I want both user and client models to share the nuts and bolts of password encryption. # app/models class User < ActiveRecord::Base include Encrypt end class Client < ActiveRecord::Base include Encrypt end # app/models/shared/encrypt.rb module Encrypt def authenticate # I want to call the ClassMethods#encrypt_password method when @user.authenticate is run self.password_crypted == self.encrypt_password(self.password) end def self.included(base) base.extend ClassMethods end module ClassMethods def encrypt_password(password) Digest::SHA1.hexdigest(password) end end end However, this fails. Says that the class method cannot be found when the instance method calls it. I can call User.encrypt_password('password') but User.new.encrypt_password fails Any thoughts?

    Read the article

  • Java Finalize method call

    - by Rajesh Kumar J
    I need to find when finalized method called in the JVM. I Created a test Class which write into file when finalized method called by Overriding the protected finalize method It is not executing. Can anybody tell me the reason why it is not executing?? Thanks in Advance

    Read the article

  • ASP.NET lock thread method

    - by Peter
    Hello, I'm developing an ASP.NET forms webapplication using C#. I have a method which creates a new Order for a customer. It looks similar to this; private string CreateOrder(string userName) { // Fetch current order Order order = FetchOrder(userName); if (order.OrderId == 0) { // Has no order yet, create a new one order.OrderNumber = Utility.GenerateOrderNumber(); order.Save(); } return order; } The problem here is, it is possible that 1 customer in two requests (threads) could cause this method to be called twice while another thread is also inside this method. This can cause two orders to be created. How can I properly lock this method, so it can only be executed by one thread at a time per customer? I tried; Mutex mutex = null; private string CreateOrder(string userName) { if (mutex == null) { mutex = new Mutex(true, userName); } mutex.WaitOne(); // Code from above mutex.ReleaseMutex(); mutex = null; return order; } This works, but on some occasions it hangs on WaitOne and I don't know why. Is there an error, or should I use another method to lock? Thanks

    Read the article

  • custom compare method in objective c

    - by Jonathan
    I'm trying to use a custom compare method (for use with sortedArrayusingSelector) and on another website I got that the format is: -(NSComparisonResult) orderByName:(id)otherobject { That's all bery well and good except how do I compare the otherObject to anything as there's only one thing passed to the method? Like how does the NSString method of compare: compare 2 strings when only one string is passed?

    Read the article

  • groovy call private method in Java super class

    - by Jeff Storey
    I have an abstract Java class MyAbstractClass with a private method. There is a concrete implementation MyConcreteClass. public class MyAbstractClass { private void somePrivateMethod(); } public class MyConcreteClass extends MyAbstractClass { // implementation details } In my groovy test class I have class MyAbstractClassTest { void myTestMethod() { MyAbstractClass mac = new MyConcreteClass() mac.somePrivateMethod() } } I get an error that there is no such method signature for somePrivateMethod. I know groovy can call private methods but I'm guessing the problem is that the private method is in the super class, not MyConcreteClass. Is there a way to invoke a private method in the super class like this (other than using something like PrivateAccessor)? thanks Jeff

    Read the article

  • Invoke private method with interface as argument

    - by Stephanie
    Hi, I've been attempting to invoke a private method whose argument is a parameter and I can't quite seem to get it right. Here's kind of how the code looks so far: public class TestClass { public TestClass(){ } private void simpleMethod( Map<String, Integer> testMap) { //code logic } } Then I attempt to use this to invoke the private method: //Hashmap Map <String, Integer> testMap = new HashMap <String, Integer>(); //method I want to invoke Method simpleMethod = TestClass.class.getDeclaredMethod("simpleMethod", Map.class); simpleMethod.setAccessible(true); simpleMethod.invoke(testClassObject, testMap); //Throws an IllegalArgumentException As you can see, it throws an IllegalArgumentException. I've attempted to cast the hashmap back to a map, but that didn't work. What am I doing wrong?

    Read the article

  • Can a C# method chain be "too long"?

    - by ccornet
    Not in terms of readability, naturally, since you can always arrange the separate methods into separate lines. Rather, is it dangerous, for any reason, to chain an excessively large number of methods together? I use method chaining primarily to save space on declaring individual one-use variables, and traditionally using return methods instead of methods that modify the caller. Except for string methods, those I kinda chain mercilessly. In any case, I worry sometimes about the impact of using exceptionally long method chains all in one line. Let's say I need to update the value of one item based on someone's username. Unfortunately, the shortest method to retrieve the correct user looks something like the following. SPWeb web = GetWorkflowWeb(); SPList list2 = web.Lists["Wars"]; SPListItem item2 = list2.GetItemById(3); SPListItem item3 = item2.GetItemFromLookup("Armies", "Allied Army"); SPUser user2 = item2.GetSPUser("Commander"); SPUser user3 = user2.GetAssociate("Spouse"); string username2 = user3.Name; item1["Contact"] = username2; Everything with a 2 or 3 lasts for only one call, so I might condense it as the following (which also lets me get rid of a would-be-superfluous 1): SPWeb web = GetWorkflowWeb(); item["Contact"] = web.Lists["Armies"] .GetItemById(3) .GetItemFromLookup("Armies", "Allied Army") .GetSPUser("Commander") .GetAssociate("Spouse") .Name; Admittedly, it looks a lot longer when it is all in one line and when you have int.Parse(ddlArmy.SelectedValue.CutBefore(";#", false)) instead of 3. Nevertheless, this is one of the average lengths of these chains, and I can easily foresee some of exceptionally longer counts. Excluding readability, is there anything I should be worried about for these 10+ method chains? Or is there no harm in using really really long method chains?

    Read the article

  • LINQ method chaining and granular error handling

    - by Clafou
    I have a method which can be written pretty neatly through method chaining: return viewer.ServerReport.GetParameters() .Single(p => p.Name == Convention.Ssrs.RegionParamName) .ValidValues .Select(v => v.Value); However I'd like to be able to do some checks at each point as I wish to provide helpful diagnostics information if any of the chained methods returns unexpected results. To achieve this, I need to break up all my chaining and follow each call with an if block. It makes the code a lot less readable. Ideally I'd like to be able to weave in some chained method calls which would allow me to handle unexpected outcomes at each point (e.g. throw a meaningful exception such as new ConventionException("The report contains no parameter") if the first method returns an empty collection). Can anyone suggest a simple way to achieve such a thing?

    Read the article

  • applet communication using post method

    - by mithun1538
    I have an applet that is communicating with a servlet. I am communicating with the servlet using POST method. My problem is how do I send parameters to the servlet. Using GET method, this is fairly simple ( I just append the parameters to the URL after a ?). But using POST method how do I send the parameters, so that in the servlet side, I can use the statement : message = req.getParameter("msg"); In the applet side, I establish POST method connection as follows : URL url = new URL(getCodeBase(), "servlet"); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type","application/octet-stream");

    Read the article

  • execute javascript method after method excution complete ?

    - by James123
    I want execute below callback()method after completion of process document.getElementById('btnDownload').click(); method. click() is the code behind method. That means, I mean after complete process of click() then excute callback() method. Because my modelpop is not hiding in code behind. So I want hide in javascript method. function LoadPopup() { // find the popup behavior this._popup = $find('mdlPopup'); // show the popup this._popup.show(); // synchronously run the server side validation ... document.getElementById('btnDownload').click(); callback(); } function callback() { this._popup = $find('mdlPopup'); // hide the popup this._popup.hide(); alert("hi"); }

    Read the article

  • A controller method that calls a different method on the same controller

    - by justSteve
    I have a controller method: public ActionResult Details(int id) { Order order = OrderFacade.Instance.Load(id); return View(order); } that is used for 95% of possible invocations. For the other 5% i need to manipulate the value of id before passing to the facade. I'd like to create a separate method within this same controller that executes that manipulation and then calls this (Details) method. What would the signature of that method look like? What is the syntax to call the main Details method? public ??? ManipulatorMethod(int id) { [stuff that manipulates id] [syntax to call Details(manipulatedID)] } mny thx

    Read the article

  • PHP: Prevent chained method from returning?

    - by Industrial
    Hi, I am having some headaches regarding method chaining for a quite simple PHP class that returns a value, which sometimes need to go through a decryption process: $dataset = new Datacontainer; $key = $dataset->get('key'); $key2 = $dataset->get('key')->decrypt(); The get method is where the return lives. So the call to the decrypt method on the second row isn't going to work in its current state. Can I do something to setup the get method to return only when nothing is chained to it, or what would be the best way to re-factor this code?

    Read the article

  • "Method name expected" error when trying add a handler method to a delegate - C#

    - by zakplayyy
    I keep getting the error "Method name expected" when trying add the a method to a delegate. I have a delegate which is invoked when ever my game ends. The function I'm trying to add to the delegate stops a countdown from flashing (the method is in a static class). I've searched about and I'm still unsure why its not working. Here is the line causing the error: LivesManager.gameEnded += new LivesManager.EndGame(CountdownManager.DisableFlashTimer(this)); The this passes the current form to the method so it can disable the timer flash on the form. I have added methods from static classes to the same delegate before and it works fine, the only difference is that I'm passing the form as a paramater and then it doesn't like it. Is there any way to pass the form to the method without the error? Thanks in advance :)

    Read the article

  • A ToDynamic() Extension Method For Fluent Reflection

    - by Dixin
    Recently I needed to demonstrate some code with reflection, but I felt it inconvenient and tedious. To simplify the reflection coding, I created a ToDynamic() extension method. The source code can be downloaded from here. Problem One example for complex reflection is in LINQ to SQL. The DataContext class has a property Privider, and this Provider has an Execute() method, which executes the query expression and returns the result. Assume this Execute() needs to be invoked to query SQL Server database, then the following code will be expected: using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // Executes the query. Here reflection is required, // because Provider, Execute(), and ReturnValue are not public members. IEnumerable<Product> results = database.Provider.Execute(query.Expression).ReturnValue; // Processes the results. foreach (Product product in results) { Console.WriteLine("{0}, {1}", product.ProductID, product.ProductName); } } Of course, this code cannot compile. And, no one wants to write code like this. Again, this is just an example of complex reflection. using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // database.Provider PropertyInfo providerProperty = database.GetType().GetProperty( "Provider", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance); object provider = providerProperty.GetValue(database, null); // database.Provider.Execute(query.Expression) // Here GetMethod() cannot be directly used, // because Execute() is a explicitly implemented interface method. Assembly assembly = Assembly.Load("System.Data.Linq"); Type providerType = assembly.GetTypes().SingleOrDefault( type => type.FullName == "System.Data.Linq.Provider.IProvider"); InterfaceMapping mapping = provider.GetType().GetInterfaceMap(providerType); MethodInfo executeMethod = mapping.InterfaceMethods.Single(method => method.Name == "Execute"); IExecuteResult executeResult = executeMethod.Invoke(provider, new object[] { query.Expression }) as IExecuteResult; // database.Provider.Execute(query.Expression).ReturnValue IEnumerable<Product> results = executeResult.ReturnValue as IEnumerable<Product>; // Processes the results. foreach (Product product in results) { Console.WriteLine("{0}, {1}", product.ProductID, product.ProductName); } } This may be not straight forward enough. So here a solution will implement fluent reflection with a ToDynamic() extension method: IEnumerable<Product> results = database.ToDynamic() // Starts fluent reflection. .Provider.Execute(query.Expression).ReturnValue; C# 4.0 dynamic In this kind of scenarios, it is easy to have dynamic in mind, which enables developer to write whatever code after a dot: using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // database.Provider dynamic dynamicDatabase = database; dynamic results = dynamicDatabase.Provider.Execute(query).ReturnValue; } This throws a RuntimeBinderException at runtime: 'System.Data.Linq.DataContext.Provider' is inaccessible due to its protection level. Here dynamic is able find the specified member. So the next thing is just writing some custom code to access the found member. .NET 4.0 DynamicObject, and DynamicWrapper<T> Where to put the custom code for dynamic? The answer is DynamicObject’s derived class. I first heard of DynamicObject from Anders Hejlsberg's video in PDC2008. It is very powerful, providing useful virtual methods to be overridden, like: TryGetMember() TrySetMember() TryInvokeMember() etc.  (In 2008 they are called GetMember, SetMember, etc., with different signature.) For example, if dynamicDatabase is a DynamicObject, then the following code: dynamicDatabase.Provider will invoke dynamicDatabase.TryGetMember() to do the actual work, where custom code can be put into. Now create a type to inherit DynamicObject: public class DynamicWrapper<T> : DynamicObject { private readonly bool _isValueType; private readonly Type _type; private T _value; // Not readonly, for value type scenarios. public DynamicWrapper(ref T value) // Uses ref in case of value type. { if (value == null) { throw new ArgumentNullException("value"); } this._value = value; this._type = value.GetType(); this._isValueType = this._type.IsValueType; } public override bool TryGetMember(GetMemberBinder binder, out object result) { // Searches in current type's public and non-public properties. PropertyInfo property = this._type.GetTypeProperty(binder.Name); if (property != null) { result = property.GetValue(this._value, null).ToDynamic(); return true; } // Searches in explicitly implemented properties for interface. MethodInfo method = this._type.GetInterfaceMethod(string.Concat("get_", binder.Name), null); if (method != null) { result = method.Invoke(this._value, null).ToDynamic(); return true; } // Searches in current type's public and non-public fields. FieldInfo field = this._type.GetTypeField(binder.Name); if (field != null) { result = field.GetValue(this._value).ToDynamic(); return true; } // Searches in base type's public and non-public properties. property = this._type.GetBaseProperty(binder.Name); if (property != null) { result = property.GetValue(this._value, null).ToDynamic(); return true; } // Searches in base type's public and non-public fields. field = this._type.GetBaseField(binder.Name); if (field != null) { result = field.GetValue(this._value).ToDynamic(); return true; } // The specified member is not found. result = null; return false; } // Other overridden methods are not listed. } In the above code, GetTypeProperty(), GetInterfaceMethod(), GetTypeField(), GetBaseProperty(), and GetBaseField() are extension methods for Type class. For example: internal static class TypeExtensions { internal static FieldInfo GetBaseField(this Type type, string name) { Type @base = type.BaseType; if (@base == null) { return null; } return @base.GetTypeField(name) ?? @base.GetBaseField(name); } internal static PropertyInfo GetBaseProperty(this Type type, string name) { Type @base = type.BaseType; if (@base == null) { return null; } return @base.GetTypeProperty(name) ?? @base.GetBaseProperty(name); } internal static MethodInfo GetInterfaceMethod(this Type type, string name, params object[] args) { return type.GetInterfaces().Select(type.GetInterfaceMap).SelectMany(mapping => mapping.TargetMethods) .FirstOrDefault( method => method.Name.Split('.').Last().Equals(name, StringComparison.Ordinal) && method.GetParameters().Count() == args.Length && method.GetParameters().Select( (parameter, index) => parameter.ParameterType.IsAssignableFrom(args[index].GetType())).Aggregate( true, (a, b) => a && b)); } internal static FieldInfo GetTypeField(this Type type, string name) { return type.GetFields( BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault( field => field.Name.Equals(name, StringComparison.Ordinal)); } internal static PropertyInfo GetTypeProperty(this Type type, string name) { return type.GetProperties( BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault( property => property.Name.Equals(name, StringComparison.Ordinal)); } // Other extension methods are not listed. } So now, when invoked, TryGetMember() searches the specified member and invoke it. The code can be written like this: dynamic dynamicDatabase = new DynamicWrapper<NorthwindDataContext>(ref database); dynamic dynamicReturnValue = dynamicDatabase.Provider.Execute(query.Expression).ReturnValue; This greatly simplified reflection. ToDynamic() and fluent reflection To make it even more straight forward, A ToDynamic() method is provided: public static class DynamicWrapperExtensions { public static dynamic ToDynamic<T>(this T value) { return new DynamicWrapper<T>(ref value); } } and a ToStatic() method is provided to unwrap the value: public class DynamicWrapper<T> : DynamicObject { public T ToStatic() { return this._value; } } In the above TryGetMember() method, please notice it does not output the member’s value, but output a wrapped member value (that is, memberValue.ToDynamic()). This is very important to make the reflection fluent. Now the code becomes: IEnumerable<Product> results = database.ToDynamic() // Here starts fluent reflection. .Provider.Execute(query.Expression).ReturnValue .ToStatic(); // Unwraps to get the static value. With the help of TryConvert(): public class DynamicWrapper<T> : DynamicObject { public override bool TryConvert(ConvertBinder binder, out object result) { result = this._value; return true; } } ToStatic() can be omitted: IEnumerable<Product> results = database.ToDynamic() .Provider.Execute(query.Expression).ReturnValue; // Automatically converts to expected static value. Take a look at the reflection code at the beginning of this post again. Now it is much much simplified! Special scenarios In 90% of the scenarios ToDynamic() is enough. But there are some special scenarios. Access static members Using extension method ToDynamic() for accessing static members does not make sense. Instead, DynamicWrapper<T> has a parameterless constructor to handle these scenarios: public class DynamicWrapper<T> : DynamicObject { public DynamicWrapper() // For static. { this._type = typeof(T); this._isValueType = this._type.IsValueType; } } The reflection code should be like this: dynamic wrapper = new DynamicWrapper<StaticClass>(); int value = wrapper._value; int result = wrapper.PrivateMethod(); So accessing static member is also simple, and fluent of course. Change instances of value types Value type is much more complex. The main problem is, value type is copied when passing to a method as a parameter. This is why ref keyword is used for the constructor. That is, if a value type instance is passed to DynamicWrapper<T>, the instance itself will be stored in this._value of DynamicWrapper<T>. Without the ref keyword, when this._value is changed, the value type instance itself does not change. Consider FieldInfo.SetValue(). In the value type scenarios, invoking FieldInfo.SetValue(this._value, value) does not change this._value, because it changes the copy of this._value. I searched the Web and found a solution for setting the value of field: internal static class FieldInfoExtensions { internal static void SetValue<T>(this FieldInfo field, ref T obj, object value) { if (typeof(T).IsValueType) { field.SetValueDirect(__makeref(obj), value); // For value type. } else { field.SetValue(obj, value); // For reference type. } } } Here __makeref is a undocumented keyword of C#. But method invocation has problem. This is the source code of TryInvokeMember(): public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder == null) { throw new ArgumentNullException("binder"); } MethodInfo method = this._type.GetTypeMethod(binder.Name, args) ?? this._type.GetInterfaceMethod(binder.Name, args) ?? this._type.GetBaseMethod(binder.Name, args); if (method != null) { // Oops! // If the returnValue is a struct, it is copied to heap. object resultValue = method.Invoke(this._value, args); // And result is a wrapper of that copied struct. result = new DynamicWrapper<object>(ref resultValue); return true; } result = null; return false; } If the returned value is of value type, it will definitely copied, because MethodInfo.Invoke() does return object. If changing the value of the result, the copied struct is changed instead of the original struct. And so is the property and index accessing. They are both actually method invocation. For less confusion, setting property and index are not allowed on struct. Conclusions The DynamicWrapper<T> provides a simplified solution for reflection programming. It works for normal classes (reference types), accessing both instance and static members. In most of the scenarios, just remember to invoke ToDynamic() method, and access whatever you want: StaticType result = someValue.ToDynamic()._field.Method().Property[index]; In some special scenarios which requires changing the value of a struct (value type), this DynamicWrapper<T> does not work perfectly. Only changing struct’s field value is supported. The source code can be downloaded from here, including a few unit test code.

    Read the article

  • Does this factory method pattern example violate open-close?

    - by William
    In Head-First Design Patterns, they use a pizza shop example to demonstrate the factory method pattern. public abstract class PizzaStore { public Pizza orderPizza(String type) { Pizza pizza; pizza = createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } abstract Pizza createPizza(String type) } public class NYPizzaStore extends PizzaStore { Pizza createPizza(String item) { if (item.equals("cheese") { return new NYStyleCheesePizza(); } else if (item.equals("veggie")) { return new NYStyleVeggiePizza(); } else if (item.equals("clam")) { return new NYStyleClamPizza(); } else if (item.equals("pepperoni")) { return new NYStylePepperioniPizza(); } else return null; } } I don't understand how this pattern is not violating open-close. What if we require a beef Pizza, then we must edit the if statement in the NYPizzaStore class.

    Read the article

  • Oracle Unified Method (OUM) 6.1

    - by user714714
    ORACLE® UNIFIED METHOD RELEASE 6.1 Oracle’s Full Lifecycle Methodfor Deploying Oracle-Based Business Solutions About | Release | Access | Previous Announcements About Oracle is evolving the Oracle® Unified Method (OUM) to achieve the vision of supporting the entire Enterprise IT Lifecycle, including support for the successful implementation of every Oracle product. OUM replaces Legacy Methods, such as AIM Advantage, AIM for Business Flows, EMM Advantage, PeopleSoft's Compass, and Siebel's Results Roadmap. OUM provides an implementation approach that is rapid, broadly adaptive, and business-focused. OUM includes a comprehensive project and program management framework and materials to support Oracle's growing focus on enterprise-level IT strategy, architecture, and governance. Release OUM release 6.1 provides support for Application Implementation, Cloud Application Services Implementation, and Software Upgrade projects as well as the complete range of technology projects including Business Intelligence (BI), Enterprise Security, WebCenter, Service-Oriented Architecture (SOA), Application Integration Architecture (AIA), Business Process Management (BPM), Enterprise Integration, and Custom Software. Detailed techniques and tool guidance are provided, including a supplemental guide related to Oracle Tutor and UPK. This release features: Project Manager and Consultant views provide quick access to material relevant to each role OUM Cloud Application Services Implementation Approach Solution Delivery Guide 3.0 and Project Workplan Template OUM Microsoft Project Workplan Template and User's Guide updated to facilitate review and removal of out-of-scope Activities and Tasks MC.050 Application Setup Template available in Microsoft Excel format in addition to Microsoft Word format BT.070 Abbreviated Project Management Framework Presentation Template Envision Examples for Enterprise Organization Structures (BA.020), Enterprise Business Context Diagram (BA.045), and High-Level Use Cases (BA.060) Implement Examples for System Context Diagram (RD.005), Business Use Case Model (RA.015), Use Case Model (RA.023), MoSCoW List (RD.045), and Analysis Specification (AN.100) Home Page drop-down menu allows access to the method by Role, Supplemental Guidance, Method Repository, or View For a comprehensive list of features and enhancements, refer to the "What's New" page of the Method Pack. Upcoming releases will provide expanded support for Oracle's Enterprise Application suites including product-suite specific materials and guidance for tailoring OUM to support various engagement types. Access Oracle Customers Oracle customers may obtain copies of the method for their internal use – including guidelines, templates, and tailored work breakdown structure – by contracting with Oracle for a consulting engagement of two weeks or longer and meeting some additional minimum criteria. Customers, who have a signed consulting contract with Oracle and meet the engagement qualification criteria, are permitted to download the current release of OUM for their perpetual use. They may also obtain subsequent releases published during a renewable, three-year access period. Training courses are also available to these customers. Contact your local Oracle Sales Representative about enrolling in the OUM Customer Program. Oracle PartnerNetwork (OPN) Diamond, Platinum, and Gold Partners OPN Diamond, Platinum, and Gold Partners are able to access the OUM method pack, training courses, and collateral from the OPN Portal at no additional cost: Go to the OPN Portal at partner.oracle.com. Select "Sign In / Register for Account". Sign In. From the Product Resources section, select "Applications". From the Applications page, locate and select the "Oracle Unified Method" link. From the Oracle Unified Method Knowledge Zone, locate the "I want to:" section. From the I want to: section, locate and select "Implement Solutions". From the Implement Solution page, locate the "Best Practices" section. Locate and select the "Download Oracle Unified Method (OUM)" link. Previous Announcements Oracle Unified Method (OUM) Release 6.1 Oracle Unified Method (OUM) Release 6.0 Oracle Unified Method (OUM) Release 5.6 Oracle Unified Method (OUM) Release 5.5 Oracle Unified Method (OUM) Release 5.4 Oracle EMM Advantage Retired Retirement of Oracle EMM Advantage Planned for December 01, 2011

    Read the article

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