w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
What's the correct way to implement a generic method to handle collections of different integral types?
One way to do this would be with compiled expressions: // helper classes which compiles a fast, type-safe delegate for writing various types static class MyBinaryWriterHelper<T> { public static readonly Action<MyBinaryWriter, T> WriteAction; // this initialization is a bit expensive, but it will occur only once // for each writable type T and will occur lazily static { // find the existing Write(T) on the MyBinaryWriter type var writeMethod = typeof(MyBinaryWriter).GetMethods() .FirstOrDefault(m => m.Name == "Write" && m.GetArguments().Length == 1 && m.GetArguments()[0](p => p.ParameterType == typeof(T) ); // if there is no such method, fail if (writeMet

Categories : C#

How to properly cast nested generic types in Java
I'm guessing you need to do a wildcard cast to cast it to what you want. List<?> j = null; List<Integer> j2 = (List<Integer>)j; List<List<?>> i = null; List<List<Integer>> i2 = (List<List<Integer>>) (List<?>) i; That compiles fine. You just needed to do an additional cast just to add a little buffer. See here: http://ideone.com/xh88lX If you want to know why, check here Basically, here's the relevant info Here's another way to look at it: Java generics is type invariant There's a conversion from Integer to Number, but a List<Integer> is not a List<Number> Similarly, a List<Integer> can be capture-converted by a List<?>, but a List<List<Integer>> is not a List<List<?>> Using

Categories : Java

Java nested wildcard bound types multiple times or as generic type parameter
If I understand what you intend to do, it would change the semantics of your class. Right now in your current class, you could have for example: class T1 extends Type {} class T2 extends Type {} class C1 extends Criteria<T1> {} class C2 extends Criteria<T2> {} class C3 extends Criteria<T2> {} class F1 extends Filter<C1> {} class Manager extends AbstractManager<F1> {} And then, even though Manager is based on F1, some user code would be perfectly legal if it did: Manager m = new Manager(); C2 c2 = new C2(); C3 c3 = new C3(); m.setCriteria(Arrays.asList(new C2[]{c2}); m.doSomethingWithCriteria(Arrays.asList(new C3[]{c3}); I don't know if it was your intent, but it is legal (from a compiler point of view). However, if you were somehow able to name that wild

Categories : Java

Generic interface implementing multiple generic types - how to share a method implementation?
Yes, given that Dog and Cat both inherit from a common base class or implement a common interface like e.g. IAnimal. Then for instance: private IEnumerable<T> ApplyFilter(IEnumerable<T> list) where T:IAnimal { // do the work here } In other words, if Cat and Dog share the filtering logic, it surely refers to a common base.

Categories : C#

xml serialize a generic class with it's generic types
Change your class as public class Pair<T, U> { [XmlAttribute("key")] public T key; [XmlAttribute("value")] public U value; [XmlAttribute("T-Type")] public string ttype; [XmlAttribute("U-Type")] public string utype; public Pair() { } public Pair(T t, U u) { key = t; value = u; ttype = typeof(T).ToString(); utype = typeof(U).ToString(); } } and it should work. You can not serialize/deserialize Type with Xmlserializer.(For example, suppose T is a complex object defined in an external assembly and this assembly does not exist on the computer where you want to deserialize)

Categories : C#

Using nested type declared in a generic class within the generic interface that the class is implementing
The only way that you can make this work is to define the procedural type outside of the implementing class. Like this: type IMyIntf<A> = interface; TMyProc<A> = reference to procedure(Intf: IMyIntf<A>); IMyIntf<A> = interface procedure Foo(Proc: TMyProc<A>); end; TMyClass<A> = class(TInterfacedObject, IMyIntf<A>) procedure Foo(Proc: TMyProc<A>); end;

Categories : Delphi

Why do generic types have the same signature?
This is not legal, since generics are discarded at runtime (this is type erasure). Both of your methods would have a prototype of Or(Object). The only solution would be to have a OrA() and OrB() method -- or review your class entirely.

Categories : Java

Is there anyway to specify the possible types for a generic class?
They are called generic type constraints. Whatever the VertexBuffer type is, it has this on that method: void SetData<T>(...) where T : struct This is what is causing your error. In fact, MSDN says that this is the method signature: public void SetData<T> ( T[] data ) where T : ValueType Which is essentially the same. So, to fix this, you'll have to pass in an array of items that are value types, not reference types. That is, your instantiation of DrawModule<T> must be DrawModule<ValueTypeHere>.

Categories : C#

Incompatible generic types
I think this post is relevant: Constraints are not part of the signature Your question hurts my brain, but I believe this is what's happening: The compiler does not "know" that TTabbedWorkspaceView is a TabbedWorkspaceView, because this information is only given through a constraint which is not part of the signature. TTabbedWorkspaceView is passed to MdiWorkspaceController as TMdiWorkspaceView, through TabbedWorkspaceController's inheritance. MdiWorkspaceController's constraint validation fails for TMdiWorkspaceView, because it was given as something that is not "known" to be an IMdiWorkspaceView. The solution: CA1005.

Categories : C#

What is difference between these Generic types
The two declarations are identical: They are both: List<String> It's the two assignments that differ. At runtime (due to type erasure) they are also identical, but at compile time you get a warning for the first one, because you're assigning a raw type to a typed variable.

Categories : Java

Collection for Generic types
Is it possible to store a map as shown in RulesExecutor sconstructor ? If not, what is the right data structure to store this info ? Sure: public interface Rule<T> { String execute(T dataProvider) } public interface DataProvider { } class RulesExecutor<T extends DataProvider> { public RulesExecutor(Map<String, List<Rule<T>>> documentToRuleListMap) { } public void executeRules(T dataProvider) { // some logic here }; } Please note that your posted code will not compile due to careless mistakes: public interface Rule<T> { String execute(T dataProvider) // *** missing semicolon } public interface DataProvider { } public class RulesExecutor() { // *** class declarations have no parenthesis Please be more careful w

Categories : Java

What are the different CLR handle types?
I have found this in my notes for windbg: #ESP - ESP=Extended Stack Pointer, Object is in use on a stack (attention, !gcroot may return false positives here, read !help gcroot in windbg) #DOMAIN(x):HANDLE(Strong) - Strong reference, Typically a static variable #DOMAIN(x):HANDLE(WeakLn) - Weak Long Handle, A weak reference that is tracked through finalization (can be resurrected) #DOMAIN(x):HANDLE(WeakSh) - Weak Short Handle, A weak reference, can't be resurrected #DOMAIN(x):HANDLE(Pinned) - Pinned object, pinned at a specific address, can't move around during garbage collection. #DOMAIN(x):HANDLE(RefCnt) - Reference count, referenced as long as the reference count is > 0. I've taken it long time ago from some MSDN blog I believe, it could have been Tess', but I can't trace it exact

Categories : Dotnet

Collection of Generic Types in Java
You can try changing the the Resource<T> to Resource <? extends State>. That way when you grab a Resource from the map you know its of type State.

Categories : Java

How to use generic types in method signature?
If I understood it right what you are trying to do, this should work: public final <T1 extends Pair<? extends Pair<? extends Enum<MyConstant>, ? extends BigDecimal>, ? extends Pair<? extends Enum<MyConstant>, ? extends BigDecimal>>> void doSomething(final int number, final T1 pair); I just hope I got the matching braces right ;-)

Categories : Java

Generic types of type variables?
Not sure if its a good way. I feel using below method you cannot "bind" the parameters m1, m2, m3 method, instead while calling you can have privilege of using any kind of parameters be it MyClass<Integer> or MyClass<String> public class MyClass<T> { } interface MyOtherClass<T extends MyClass<?>> { void m1(T argument); void m2(T argument); void m3(T argument); } And the implementer class MyOtherClassImpl<T extends MyClass<?>> implements MyOtherClass<T> { @Override public void m1(T argument) { } @Override public void m2(T argument) { } @Override public void m3(T argument) { } } and this is how you can call MyOtherClass<MyClass<?>> otc = new MyOtherClassImpl<MyClass<?

Categories : Java

Generic Method for Numeric Types
This cannot be done, because you cannot constrain a generic type to a group of numeric types (Integer, Long, Decimal, Double). The problem is that there is no IArithmetic interface that you could you use to constrain T to, therefore you cannot write this: ' This does not work because IArithmetic does not exist <Extension()> _ Public Function Add(Of T As IArithmetic)(a As T, b As T) As T Return a + b End Function However, you can join the cause to convince Microsoft to implement this by the Microsoft Feedback Center and proposing and/or commenting on similar requests.

Categories : Vb.Net

Accessing members of generic value types in C#
Implement a common interface for both structs and change fields to properties. interface ISomething { Double X{ get;} Double Y{ get;} Double Z{ get;} } then add this interface as generic constraint. You're done Note: as @Jon pointed generic constraints wont box the valuetypes.

Categories : C#

Deserializing Generic Types with GSON
Have you tried? gson.create().fromJson(reader, MyJson.class); EDIT After reading this post it seems that you use of Type is correct. I believe your issue is the use of T. You must remember that with Java there is type-erasure. This means that at runtime all instances of T are replaced with Object. Therefore at runtime what you are passing GSON is really MyJson<Object>. If you tried this with a concrete class in place of <T> I believe it would work. Google Gson - deserialize list<class> object? (generic type)

Categories : Java

Generic Types Related But Incompatible
Change your code public interface FileStructureLevel<E extends FileStructureLevel> extends NodeStructureLevel<FileStructureLevel> to public interface FileStructureLevel<E extends FileStructureLevel> extends NodeStructureLevel<E> and everybody will be happy. As it stands, a FileStructureLevel<L> is not a NodeStructureLevel<L> as required by NodeStructure, but is instead a NodeStructureLevel<FileStructureLevel>. This is what the compiler is trying to tell you.

Categories : Java

Casting back on generic types
Your generic has a constraint that says that DbTransactionType needs to be the class DbTransaction or any class derived from it. With that highlight, it should be clear that you shouldn't even explicitly cast it. But if it is not clear: The return value of BeginTransaction is an instance of type DbTransaction. The type of _transaction is DbTransactionType which could be a sub-class of DbTransaction. You can't assign a variable of a base class to a variable of a sub-class without casting. And the cast will only work if the variable of the base class actually contains an instance of that sub-class. When thinking about this problem, in your mental model replace DbTransactionType with string and DbTransaction with object. Now the problem should become clear immediately.

Categories : C#

Raw types inside of generic definition
The difference is that when you use class MyClass<T extends List> { } inside MyClass you lose type safety. for example: class A <T extends List<?>>{ void someFunc(T t) { t.add(new Object());//compilation error } } class B <T extends List>{ void someFunc(T t) { //compiles fine t.add(new Object()); t.add("string"); t.add(new Integer(3)); } }

Categories : Java

Possible types of elements for generic collections
List<? super MyClass> - contains something that is superclass of MyClass, which means that you can put only MyClass and it superclasses here. List<? extends MyClass> - contains something that extends MyClass, which means that you can't add anything here (because you don't know which subclass is used exactly). Although you can say for sure, that items are MyClass (or subclasses). List<T extends MyClass> - contains T, that is subclass of MyClass. Can only add T and subclasses of it.

Categories : Java

Casting generic types without warning?
You need to declare the generic type V in your method like this: public <V> JAXBElement<V> unmarshal(..., Class<V> valueType) Other than that, I can't find any mistakes in your code.

Categories : Java

Define Generic Types with String
Look: def createMap[foo, bar] = { Map[foo, bar]() } val myMap = createMap[`String`, `Int`] Doesn't it look similar to the required code? If you really wish to create a map at runtime with types unknown at compile time, then you can simply use Map[Any, Any]() + type casts. I don't think it is possible to achieve type safety with string type identifiers. (To obtain a class for runtime check see another question) It seems that macros can be used. However I'm not an expert to provide the implementation.

Categories : Scala

how to pass generic types to Argonaut
It seems that Argonaut, like pretty much all scala serialization libraries, uses the type class pattern. This sounds like a fancy thing, but actually it just means that when serializing/deserializing an object of type T, it needs you to implicitly pass an instance of another object to which part or all of the process is deferred to. Specifically, when you do decodeOption[T], you need to have in scope an instance of argonaut.DecodeJson[T] (which decodeOption will use during the deserialization). What you should do is simply to require this implicit value to be passed to Parse (it will then automatically be passed along to decodeOption: def Parse[T](input: String)(implicit decoder: argonaut.DecodeJson[T]): Option[T] = { input.decodeOption[T] } Scala even provides some syntactic sugar t

Categories : Scala

Is there a way to define generic types in JS documentation?
Interestingly, Google Closure Compiler has support for generic types, with a syntax like this: /** * @constructor * @template T */ Foo = function() { ... }; /** @return {T} */ Foo.prototype.get = function() { ... }; /** @param {T} t */ Foo.prototype.set = function(t) { ... }; /** @type {!Foo.<string>} */ var foo = new Foo(); var foo = /** @type {!Foo.<string>} */ (new Foo()); As JSDuck already supports Closure Compiler style type annotations, it should be already possible to write types like {MyClass.<T>}. JSDuck doesn't however uses a @template tag for a different purpose altogether, but one implement its own custom tag like @typevar or override the builtin @template to do your bidding using the custom tags system. But as there is no actual generic types suppor

Categories : Javascript

variable length generic types
If you need variable-length keys, you can use javatuples or something similar, which wrap an arbitrary number and arbitrary types of arguments (they provide tuples until a length of 10): Map<Triplet<Double,Float,Integer>, Object> mapWithCombinedKeys = ...

Categories : Java

Specify valid generic types with a parameter
This is indeed a tricky issue for the reasons you've pointed out. I tried various approaches but they were all defeated by the generics limitation you cited. Ultimately it seems like you'll need to make some design changes if you want the specified type safety. Using the inheritance hierarchy of the SortBy implementations for your generic type restrictions seems to have led to this impasse in particular. I tried decoupling that restriction into a new type parameter on SortBy, which stands for the queried object itself, e.g. Comment, User, etc. This is the design I came up with: static class Comment { } static class User { } interface SortBy<T, M> { } static class CommentSortBy<M> implements SortBy<Comment, M> { static final CommentSortBy<Date> CREATION = n

Categories : Java

Interfaces and methods with generic types
You can merely use a List<object>, but if you want to do it the way you propose then you need to create an interface with a signature that covers both your classes public interface IGen { int A; int Method; } Then inherit/implement this interface in your classes public class Pet : IGen { public int A { get; set; } private int Method(){ ... } } public class Book : IGen { public int A { get; set; } private int Method(){ ... } } Then you can pass into your GetSubSet like GetSubSet<IGen>(List<IGen> incomingList) { ... } I hope this helps.

Categories : C#

Open Generic types won't register in the catalog
Any idea what triggered it to start failing? Did you get a .NET update in that timeframe? Out of curiosity if you write a simple console app targeting .NET 4.5 does this issue repro? The reason I ask is I believe there was an update released for .NET 4.5 to make sure open generics didn't break existing .NET 4.0 apps and so if for some reason your tests are running in .NET 4.0 mode then then the open generic support will be disabled which could cause what you are seeing.

Categories : C#

Linked List with Generic Types Troubles
First off, your print method doesn't even try to print the leading text ("The list is:"), and it prints each item on its own line. Given that, it looks like the problem is with insertAtBack: the arguments to making your new ListNode are backwards (the new node should come AFTER what was the last node, temp node).

Categories : Java

Do custom generic types work with precompile?
As far as protobuf-net is concerned, OneTwo<Foo> is largely unrelated to OneTwo<Bar>, and OneTwo<> (the open generic type) is meaningless. It is preparing a strategy separately for each OneTwo<{something}> the first time it sees each type. Your best net is to trick precompile into knowing the T you intend on using at runtime. Perhaps: [ProtoContract, Obsolete("this is not the class you are looking for", true)] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public class BagOfEvil { [ProtoMember(1)] public OneTwo<Foo> Foo {get;set;} [ProtoMember(2)] public OneTwo<Bar> Bar {get;set;} ... } Now it knows about the concrete types you will be using.

Categories : Dotnet

Raw type. References to generic types should be parameterized
Cage<T> is a generic type, so you need to specify a type parameter, like so (assuming that there is a class Dog extends Animal): private Cage<Dog> cage5 = new Cage<Dog>(5); You can use any type that extends Animal (or even Animal itself). If you omit the type parameter then what you wind up with in this case is essentially Cage<Animal>. However, you should still explicitly state the type parameter even if this is what you want.

Categories : Java

Generic constrained Map using higher-kinded-types?
In your case you can use simple solution (only changed code): abstract class Resolver[T <: Result] { def result(): T } object Loader { val cache = collection.mutable.Map[Resolver[_], Any] () def get[K <: Result](k: Resolver[K]): K = { cache.getOrElseUpdate(k, { k.result } ).asInstanceOf[K] } }

Categories : Scala

Infer generic types on scala shell
Perhaps scala> object Foo { | type A = Int | type B = Int | } defined object Foo scala> import Foo._ import Foo._ scala> :type Future.traverse[A,B,List] _ List[Foo.A] => ((Foo.A => scala.concurrent.Future[Foo.B]) => scala.concurrent.Future[List[Foo.B]])

Categories : Scala

How come I can define generic exception types in Scala?
Here is the answer we carved out so far in the discussion. Is this well defined according to the JLS and JVM spec or does it just happen to work accidentally? It does not have to be well defined according to the Java Language Specification, as it is a different Language. The JVM, OTOH, has no problems throwing and catching such exceptions, because due to type erasure, it makes no difference in the bytecode. Nevertheless, the interesting question remains, why Java forbids extension of Throwable with generic classes in the first place.

Categories : Java

Generic Types, compiler and dynamic languages
The statement is true. With generic types you specify a type when you instantiate the object and its use may be checked at compile time. Without a type parameter on a class there is no way to check.

Categories : Misc

PDO handle value types (int or varchar)
also at this question - the problem are the missing backticks. setting up the query ($sql) like this, does the trick. $sql = "UPDATE `clients` SET `$key` = :value WHERE id = :recid"; before and after table and column name use backticks `

Categories : PHP

Extension method selection using generic types and Expressions
Generics are not dynamic typing. Which overload to call is frozen at compile-time. When the program is later run, even if the variable happens to hold a more specific run-time type, that doesn't matter because the overload was fixed at compile-time. Your method: public string TestExt() { return this.Ext(a => a.Content); } has to bind at compile-time to one specific overload of Ext. Since all we know about T (the type of a.Content) in the class MyClass<T> is that it is convertible to object, there is really only one overload to choose from, so this is easy for the compiler. From then on, the TestExt method body is hard-coded to calling that specific overload of Ext. EDIT: Here's a much simpler example: static void Main() { IEnumerable<object> e = new List<

Categories : C#

C# generics: any way to refer to the generic parameter types as a collection?
No. You can not use the Type parameter as you want. But you could use something like Tuple. It allows you to Wrap generics. But you can not use the TypeParamter itself.

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.