Search Results

Search found 1008 results on 41 pages for 'generics'.

Page 26/41 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • How to infer the type of a derived class in base class?

    - by enzi
    I want to create a method that allows me to change arbitrary properties of classes that derive from my base class, the result should look like this: SetPropertyValue("size.height", 50); – where size is a property of my derived class and height is a property of size. I'm almost done with my implementation but there's one final obstacle that I want to solve before moving on, to describe this I will first have to explain my implementation a bit: Properties that can be modified are decorated with an attribute There's a method in my base class that searches for all derived classes and their decorated properties For each property I generate a "property modifier", a class that contains 2 delegates: one to set and one to get the value of the property. Property Modifiers are stored in a dictionary, with the name of the property as key In my base class, there is another dictionary that contains all property-modifier-dictionaries, with the Type of the respective class as key. What the SetPropertyValue method does is this: Get the correct property-modifier-dictionary, using the concrete type of the derived class (<- yet to solve) Get the property modifier of the property to change (e.g. of the property size) Use the get or set delegate to modify the property's value Some example code to clarify further: private static Dictionary<RuntimeTypeHandle, object> EditableTypes; //property-modifier-dictionary protected void SetPropertyValue<T>(EditablePropertyMap<T> map, string property, object value) { var property = map[property]; // get the property modifier property.Set((T)this, value); // use the set delegate (encapsulated in a method) } In the above code, T is the Type of the actual (derived) class. I need this type for the get/set delegates. The problem is how to get the EditablePropertyMap<T> when I don't know what T is. My current (ugly) solution is to pass the map in an overriden virtual method in the derived class: public override void SetPropertyValue(string property, object value) { base.SetPropertyValue((EditablePropertyMap<ExampleType>)EditableTypes[typeof(ExampleType)], property, value); } What this does is: get the correct dictionary containing the property modifiers of this class using the class's type, cast it to the appropiate type and pass it to the SetPropertyValue method. I want to get rid of the SetPropertyValue method in my derived class (since there are a lot of derived classes), but don't know yet how to accomplish that. I cannot just make a virtual GetEditablePropertyMap<T> method because I cannot infer a concrete type for T then. I also cannot acces my dictionary directly with a type and retrieve an EditablePropertyMap<T> from it because I cannot cast to it from object in the base class, since again I do not know T. I found some neat tricks to infere types (e.g. by adding a dummy T parameter), but cannot apply them to my specific problem. I'd highly appreciate any suggestions you may have for me.

    Read the article

  • Getting the constructor of an Interface Type through reflection?

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

    Read the article

  • Autocomplete for generic types in Eclipse

    - by AvrDragon
    "Refer to objects by their interfaces" is a good practise, as mentioned in Effective Java. So for example i prefer List<String> al = new ArrayList<String>(); over ArrayList<String> al = new ArrayList<String>(); in my code. One annoying thing is that if i type ArrayList<String> al = new and then hit Ctrl+Space in Eclipse i get ArrayList<String>() as propostal. But if i type List al = new and then hit Ctrl+Space i will get only propostal to define anonymous inner class, but not propostals such as new ArrayList<String>(), what is 99% the case, or for example new Vector<String>(). Is there any way to get the subclasses as propostals for generic types?

    Read the article

  • Iterating over member typed collection fails when using untyped reference to generic object

    - by Alexander Pavlov
    Could someone clarify why iterate1() is not accepted by compiler (Java 1.6)? I do not see why iterate2() and iterate3() are much better. This paragraph is added to avoid silly "Your post does not have much context to explain the code sections; please explain your scenario more clearly." protection. import java.util.Collection; import java.util.HashSet; public class Test<T> { public Collection<String> getCollection() { return new HashSet<String>(); } public void iterate1(Test test) { for (String s : test.getCollection()) { // ... } } public void iterate2(Test test) { Collection<String> c = test.getCollection(); for (String s : c) { // ... } } public void iterate3(Test<?> test) { for (String s : test.getCollection()) { // ... } } } Compiler output: $ javac Test.java Test.java:11: incompatible types found : java.lang.Object required: java.lang.String for (String s : test.getCollection()) { ^ Note: Test.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 1 error

    Read the article

  • is there some lightweight tecnique for adding type safety to identifier properties?

    - by shoren
    After using C++ I got used to the concept of Identifier which can be used with a class for the type, provides type safety and has no runtime overhead (the actual size is the size of the primitive). I want to do something like that, so I will not make mistakes like: personDao.find(book.getId());//I want compilation to fail personDao.find(book.getOwnerId());//I want compilation to succeed Possible solutuions that I don't like: For every entity have an entity id class wrapping the id primitive. I don't like the code bloat. Create a generic Identifier class. Code like this will not compile: void foo(Identifier book); void foo(Identifier person); Does anyone know of a better way? Is there a library with a utility such as this? Is implementing this an overkill? And the best of all, can this be done in Java without the object overhead like in C++?

    Read the article

  • Creating parameterized type object using annonymous class

    - by Andrei Fierbinteanu
    This might be a stupid question, but I just saw a question asking how to create a Type variable for a generic type. The consensus seemed to be that you should have a dummy method returning that type, and then use reflection to get it (in this case he wanted Map<String, String>). Something like this : public Map<String, String> dummy() { throw new Error(); } Type mapStringString = Class.forName("ThisClass").getMethod("dummy").getGenericReturnType(); My question is, not having used reflection that much, couldn't you just do something like: Type mapStringString = new ParameterizedType() { public Type getRawType() { return Map.class; } public Type getOwnerType() { return null; } public Type[] getActualTypeArguments() { return new Type[] { String.class, String.class }; } }; Would this work? If not, why not? And what are some of the dangers/problems if it does (besides being able to return some Type like Integer<String> which is obviously not possible.

    Read the article

  • understanding syb boilerplate elimination

    - by Pradeep
    In the example given in http://web.archive.org/web/20080622204226/http://www.cs.vu.nl/boilerplate/ -- Increase salary by percentage increase :: Float -> Company -> Company increase k = everywhere (mkT (incS k)) -- "interesting" code for increase incS :: Float -> Salary -> Salary incS k (S s) = S (s * (1+k)) how come increase function compiles without binding anything for the first Company mentioned in its type signature. Is it something like assigning to a partial function? Why is it done like that?

    Read the article

  • F# compilation error: Unexpected type application

    - by Jim Burger
    In F#, given the following class: type Foo() = member this.Bar<'t> (arg0:string) = ignore() Why does the following compile: let f = new Foo() f.Bar<Int32> "string" While the following won't compile: let f = new Foo() "string" |> f.Bar<Int32> //The compiler returns the error: "Unexpected type application"

    Read the article

  • Map inheritance from generic class in Linq To SQL

    - by Ksenia Mukhortova
    Hi everyone, I'm trying to map my inheritance hierarchy to DB using Linq to SQL: Inheritance is like this, classes are POCO, without any LINQ to SQL attributes: public interface IStage { ... } public abstract class SimpleStage<T> : IStage where T : Process { ... } public class ConcreteStage : SimpleStage<ConcreteProcess> { ... } Here is the mapping: <Database Name="NNN" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"> <Table Name="dbo.Stage" Member="Stage"> <Type Name="BusinessLogic.Domain.IStage"> <Column Name="ID" Member="ID" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" /> <Column Name="StageType" Member="StageType" IsDiscriminator="true" /> <Type Name="BusinessLogic.Domain.SimpleStage" IsInheritanceDefault="true"> <Type Name="BusinessLogic.Domain.ConcreteStage" IsInheritanceDefault="true" InheritanceCode="1"/> </Type> </Type> </Table> </Database> In the runtime I get error: System.InvalidOperationException was unhandled Message="Mapping Problem: Cannot find runtime type for type mapping 'BusinessLogic.Domain.SimpleStage'." Neither specifying SimpleStage, nor SimpleStage<T> in mapping file helps - runtime keeps producing different types of errors. DC is created like this: StreamReader sr = new StreamReader(@"MappingFile.map"); XmlMappingSource mapping = XmlMappingSource.FromStream(sr.BaseStream); DataContext dc = new DataContext(@"connection string", mapping); If Linq to SQL doesn't support this, could you, please, advise some other ORM, which does. Thanks in advance, Regards! Ksenia

    Read the article

  • Can i use a generic implicit or explicit operator? C#

    - by acidzombie24
    How do i change the following statement so it accepts any type instead of long? Now here is the catch, if there is no constructor i dont want it compiling. So if theres a constructor for string, long and double but no bool how do i have this one line work for all of these support types? ATM i just copied pasted it but i wouldnt like doing that if i had 20types (as trivial as the task may be) public static explicit operator MyClass(long v) { return new MyClass(v); }

    Read the article

  • removing items from a generic List<t>

    - by frosty
    I have the following method, I wish to remove items from my collection that match the product Id. Seems fairly straight forward, but i get an exception. Basically my collection is getting out of sync. So what is the best way to remove an item from a collection. public void RemoveOrderItem(Model.Order currentOrder, int productId) { foreach (var orderItem in currentOrder.OrderItems) { if (orderItem.Product.Id == productId) { currentOrder.OrderItems.Remove(orderItem); } } } Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute

    Read the article

  • c# Why can't open generic types be passed as parameters?

    - by Rich Oliver
    Why can't open generic types be passed as parameters. I frequently have classes like: public class Example<T> where T: BaseClass { public int a {get; set;} public List<T> mylist {get; set;} } Lets say BaseClass is as follows; public BaseClass { public int num; } I then want a method of say: public int MyArbitarySumMethod(Example example)//This won't compile Example not closed { int sum = 0; foreach(BaseClass i in example.myList)//myList being infered as an IEnumerable sum += i.num; sum = sum * example.a; return sum; } I then have to write an interface just to pass this one class as a parameter as follows: public interface IExample { public int a {get; set;} public IEnumerable<BaseClass> myIEnum {get;} } The generic class then has to be modified to: public class Example<T>: IExample where T: BaseClass { public int a {get; set;} public List<T> mylist {get; set;} public IEnumerable<BaseClass> myIEnum {get {return myList;} } } That's a lot of ceremony for what I would have thought the compiler could infer. Even if something can't be changed I find it psychologically very helpful if I know the reasons / justifications for the absence of Syntax short cuts.

    Read the article

  • How can I make this code more generic

    - by Greg
    Hi How could I make this code more generic in the sense that the Dictionary key could be a different type, depending on what the user of the library wanted to implement? For example someone might what to use the extension methods/interfaces in a case where there "unique key" so to speak for Node is actually an "int" not a "string" for example. public interface ITopology { Dictionary<string, INode> Nodes { get; set; } } public static class TopologyExtns { public static void AddNode(this ITopology topIf, INode node) { topIf.Nodes.Add(node.Name, node); } public static INode FindNode(this ITopology topIf, string searchStr) { return topIf.Nodes[searchStr]; } } public class TopologyImp : ITopology { public Dictionary<string, INode> Nodes { get; set; } public TopologyImp() { Nodes = new Dictionary<string, INode>(); } }

    Read the article

  • How to convert value of Generic Type Argument to a concrete type?

    - by Aleksey Bieneman
    I am trying to convert the value of the generic type parameter T value into integer after making sure that T is in fact integer: public class Test { void DoSomething<T>(T value) { var type = typeof(T); if (type == typeof(int)) { int x = (int)value; // Error 167 Cannot convert type 'T' to 'int' int y = (int)(object)value; // works though boxing and unboxing } } } Although it works through boxing and unboxing, this is an additional performance overhead and i was wandering if there's a way to do it directly. Thank you!

    Read the article

  • Convert Text with newlines to a List<String>

    - by Vaccano
    I need a way to take a list of numbers in string form to a List object. Here is an example: string ids = "10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19"; List<String> idList = new List<String>(); idList.SomeCoolMethodToParseTheText(ids); <------+ | foreach (string id in idList) | { | // Do stuff with each id. | } | | // This is the Method that I need ----------------+ Is there something in the .net library so that I don't have to write the SomeCoolMethodToParseTheText myself?

    Read the article

  • Convert IDictionary to Dictionary

    - by croisharp
    I have to convert System.Collections.Generic.IDictionary<string, decimal> to System.Collections.Generic.Dictionary<string, decimal>, and i can't. I tried the ToDictionary method and can't specify right arguments. I've tried the following: // my dictionary is PlannedSurfaces (of type IDictionary<string, decimal>) blabla.ToDictionary<string, decimal>(localConstruction.PlannedSurfaces)

    Read the article

  • How to find the class object of Java generic type?

    - by Samuel Yung
    Assume I have a generic type P which is an Enum, that is <P extends Enum<P>>, and I want to get the Enum value from a string, for example: String foo = "foo"; P fooEnum = Enum.valueOf(P.class, foo); This will get a compile error because P.class is invalid. So what can I do in order to make the above code work?

    Read the article

  • C# Generic List constructor gives me a MethodAccessException

    - by evilfred
    Hi, I make a list in my code like so: List<IConnection> connections = new List<IConnection>(); where IConnection is my own interface. This is in a .NET 2.0 executable. If I run the code on my machine (with lots of .Net versions installed) it works fine. If I run it on my test machine (which only has .NET 3.5 SP1 installed) then I get a MethodAccessException in the System.Collections.Generic.List constructor. Any ideas what could be going wrong?

    Read the article

  • C# - Why can't I enforce derived classes to have parameterless constructors?

    - by FrisbeeBen
    I am trying to do the following: public class foo<T> where T : bar, new { _t = new T(); private T _t; } public abstract class bar { public abstract void someMethod(); // Some implementation } public class baz : bar { public overide someMethod(){//Implementation} } And I am attempting to use it as follows: foo<baz> fooObject = new foo<baz>(); And I get an error explaining that 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. I fully understand why this must be, and also understand that I could pass a pre-initialized object of type 'T' in as a constructor argument to avoid having to 'new' it, but is there any way around this? any way to enforce classes that derive from 'bar' to supply parameterless constructors?

    Read the article

  • Unit test approach for generic classes/methods

    - by Greg
    Hi, What's the recommended way to cover off unit testing of generic classes/methods? For example (referring to my example code below). Would it be a case of have 2 or 3 times the tests to cover testing the methods with a few different types of TKey, TNode classes? Or is just one class enough? public class TopologyBase<TKey, TNode, TRelationship> where TNode : NodeBase<TKey>, new() where TRelationship : RelationshipBase<TKey>, new() { // Properties public Dictionary<TKey, NodeBase<TKey>> Nodes { get; private set; } public List<RelationshipBase<TKey>> Relationships { get; private set; } // Constructors protected TopologyBase() { Nodes = new Dictionary<TKey, NodeBase<TKey>>(); Relationships = new List<RelationshipBase<TKey>>(); } // Methods public TNode CreateNode(TKey key) { var node = new TNode {Key = key}; Nodes.Add(node.Key, node); return node; } public void CreateRelationship(NodeBase<TKey> parent, NodeBase<TKey> child) { . . .

    Read the article

  • How do I make lambda functions generic in Scala?

    - by Electric Coffee
    As most of you probably know you can define functions in 2 ways in scala, there's the 'def' method and the lambda method... making the 'def' kind generic is fairly straight forward def someFunc[T](a: T) { // insert body here what I'm having trouble with here is how to make the following generic: val someFunc = (a: Int) => // insert body here of course right now a is an integer, but what would I need to do to make it generic? val someFunc[T] = (a: T) => doesn't work, neither does val someFunc = [T](a: T) => Is it even possible to make them generic, or should I just stick to the 'def' variant?

    Read the article

  • Create instance of generic type in Java?

    - by David Citron
    Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is "no" (due to type erasure), but I'd be interested if anyone can see something I'm missing: class SomeContainer<E> { E createContents() { return what??? } } EDIT: It turns out that Super Type Tokens could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated. I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's Artima Article.

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >