w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Check if a type implements a generic interface without considering the generic type arguments
As far as I know, the only way to do this is to get all interfaces and see if the generic definition matches the required interface type. bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()) .Contains(typeof(MyInterface<,>)); EDIT: As Jon points out in the comments, you could also do: bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == typeof(MyInterface<,>));

Categories : C#

Why isn't a generic type recognized as its derived type when passed as a generic parameter?
It is because you have list of Predicates. When you get element from list it is still only a base class. In runtime it will be a derived class, but generic works durring compilation.

Categories : C#

What is the benefit of extending a generic by specifying the new type as actual type of generic
You might do something like this when dealing with recursive data structures. For example, nodes in a graph or a tree could be defined as a collection of other nodes: class Node extends AbstractList<Node> { ... } Equally you might see something like this if the abstract/generic type is meant for comparing objects of a similar type, such as is the case with java.lang.Comparable: class MyObject implements Comparable<MyObject> { public int compareTo(MyObject other) { ... } }

Categories : Java

How to make Generic Type as out type if it is reference Type?
If you have an error with the return type of IEnumerable<IGrouping<string, MyClass>> in a generic class that has been declared using <T>, then I'm guessing that your return type should actually be IEnumerable<IGrouping<string, T>>... of course, without seeing your code, this can only be a guess.

Categories : C#

JsonCovert.DeserializeObject is loading the object type but none of the Json Fields
For posterity: RootObject ro = new RootObject(); try { StreamReader sr = new StreamReader(FileLoc); string jsonString = sr.ReadToEnd(); JavaScriptSerializer ser = new JavaScriptSerializer(); ro = ser.Deserialize<RootObject>(jsonString); } you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client

Categories : C#

How to use a generic type parameter as type parameter for a property declared as an interface with type constraints?
Try to add class constraint to the TItem: namespace Sample2 { public interface IInterfaceContainer<T1, T2> where T1 : T2 { } public interface IInterfaceParent { } public interface IInterfaceChild : IInterfaceParent { } public class ClassSampleDoesNotWork<TItem> where TItem : class, IInterfaceParent { IInterfaceContainer<IEnumerable<TItem>, IEnumerable<IInterfaceParent>> SomeProperty { get; set; } } } This works because variance only works for reference-types (or there is an identity conversion). It isn't known that TItem is reference type, unless you add : class. Read this article for more information. Here is a sample code to demonstrate this behavior: IEnumerable<Object> ite

Categories : C#

Serialize complex type as simple type JSON
import this namespace System.Web.Script.Serialization; string SerializeObject() { var objs = new List<Test>() var objSerialized = new JavaScriptSerializer(); return objSerialized .Serialize(objs); } I use as example a List but you will use your object instead.

Categories : C#

Java Pass instance type of Object to generic class type parameter
No.. generic type should be known at compile time. Generics are there to catch possible runtime exceptions at compile time itself. List<Integer> list = new ArrayList<Integer>(); //..some code String s = list.get(0); // this generates compilation error because compiler knows that list is meant to store only Integer objects and assigning the value got from list to String is definitely an error. If the generic type was determined at run-time this would have been difficult.

Categories : Java

Create instance of generic type in Java when parameterized type passes through hierarchies?
getClass().getGenericSuperclass(); gives you the details of the super class. Therefore it will only work if you subclass a parameterized super class. It won't work if you instantiate a parameterized super class given type parameters.

Categories : Java

Using a generic type argument in place of an argument of type System.Type. Is it a smell?
Methods that deal with types usually do just that: Dealing with types. IMO, Class.Method<SomeType>(); is much better than Class.Method(typeof(SomeType)); But that is a matter of opinion I guess. Consider LINQ's .OfType<T>(), for example: personlist.OfType<Employee>().Where(x => x.EmployeeStatus == "Active"); versus: personlist.OfType(typeof(Employee)).Where(x => ((Employee)x).EmployeeStatus == "Active"); which one would you prefer?

Categories : C#

Create instance of generic type in Java when parameterized type is contained?
The anonymous class must have the actual type parameter hard-coded in its declaration for it to work. new Parameterized<E>(){}; does not work. You are just hard-coding "E" (a type variable). So when you look at the metadata using reflection all you see is "E" (a type variable). You must create a subclass which hard-codes its superclass with an actual class as type argument at compile-time: new Parameterized<String>(){}; I tried to adapt Steve B's approach of creating an anonymous subclass: You missed the whole point of that. The point was not to create a subclass. The point was to create a subclass with the actual class of the type argument hard-coded in the superclass.

Categories : Java

How to return correct type from generic function passed a related abstract type parameter
I am just going to reiterate my own (current) "answer" for my question, because I thought it would be interesting/instructive to allow readers to vote it up or down to generate a more direct comparison with answers provided by others. trait Context { // ... other stuff ... protected val aList: List[A] protected val bList: List[B] protected val cList: List[C] def get[R <: Referenced](ref: R#refType): Option[R] = { val result = ref match { case aRef: ARef => aList.find(_.ref == aRef) case bRef: BRef => bList.find(_.ref == bRef) case cRef: CRef => cList.find(_.ref == cRef) case _ => throw new RuntimeException("Unknown Ref type for retrieval: "+ref) } result.asInstanceOf[Option[R]] } }

Categories : Scala

Inferred type is not a valid substitute for a Comparable generic type
Actually more detailed explanation of this error gives your javac itself: java: no suitable method found for sort(java.util.ArrayList<MyItem<V>>) method java.util.Collections.<T>sort(java.util.List<T>,java.util.Comparator<? super T>) is not applicable (cannot instantiate from arguments because actual and formal argument lists differ in length) method java.util.Collections.<T>sort(java.util.List<T>) is not applicable (inferred type does not conform to declared bound(s) inferred: MyItem<V> bound(s): java.lang.Comparable<? super MyItem<V>>) So, the main question is: why is method Collections.<T>sort(java.util.List<T>)) not applicable? The answer is: because in Collections.<T>sort(java.util.List<

Categories : Java

Get actual type of generic type argument on abstract superclass
Common way to sort this issue in a secure way is to add a constructor to store the class of the type. Example in your context: public abstract class BaseDao<T extends PersistentObject> { private Class<T> classT; BaseDao(Class<T> classT){ this.classT=classT; } protected Class<T> getClazz() { return classT; } // ... }

Categories : Java

How do I resolve the actual type for a generic return type using reflection?
At runtime, it returns Object because of type-erasure which replaces all generic types with Object. There is no way to determine at runtime what generic type was provided at compile-time. type-erasure

Categories : Java

Autofac - Returning Concrete Type For Abstract Generic Type
After struggling to find a way of integrating Steven's solution with Autofac, I came across Patrick Desjardin's blog post: The three layers of validation (Controller, Service & Repository). I found it easy as you don't have to inject any Validation Providers. Also, it is easy to be integrated with any layer. Please make sure you read the follow up posts as well: How to validate model object with Asp.Net MVC correctly Model validation and Entity Framework 4.3 Any opinions that compares both solutions would be much appreciated. Many thanks!

Categories : C#

Casting between an object of generic type "T" and an object of generic type ">"
Based on the exception, it looks like you're initializing element with new Object[someLength] and doing an unchecked cast to T[]. This is likely happening in ArrayLinearList. The problem is that in this code: element[ pedro ] = maria; element is treated as a Comparable[] at runtime, and an Object[] isn't a Comparable[]. There are many existing posts related to generic array creation, but your issue is interesting because you've thrown inheritance into the mix (with a narrowing of a type parameter's bounds). The best solution seems to be only interacting with element within the ArrayLinearList class. Make it private and expose getters and setters. This should avoid runtime failures like this (which take some thought to avoid when doing unchecked casts like (T[])new Object[someLength]).

Categories : Java

Using weka in C#: Unable to cast object of type 'java.util.ArrayList' to type 'System.Collections.Generic.List`
I am answering my own question. I used this link to solve the problem I was facing. Thanks @SecretSquirrel(see the comments) and @Jon Iles (see the answer I've linked).

Categories : C#

C#, instantiating a generic type - with variable type argument?
You can do it with reflection var entryType = typeof(Entry<>); Type[] typeArgs = { o.GetType() }; var genericType = entryType.MakeGenericType(typeArgs); IEntry entry = (IEntry)Activator.CreateInstance(genericType);

Categories : C#

Generic Method Return Type as Type parameter
Is this what you are looking for? I've added an extra catch for cases where the cast isn't valid also Decimal i = stringName.ToType<Decimal>(); public static T ToType<T>(this string value) { object parsedValue = default(T); try { parsedValue = Convert.ChangeType(value, typeof(T)); } catch (InvalidCastException) { parsedValue = null; } catch (ArgumentException) { parsedValue = null; } return (T)parsedValue; } Edit a shortcut approach to fix Anton's comment if (typeof(T).IsValueType) return default(T);

Categories : C#

Type inference when inheriting generic type and constraint
If you could omit the type parameter, there would be nothing to prevent you from having a single class that implemented both IStringToTypeConverter<Foo> and IStringToTypeConverter<Bar>. If that class did both, which type can it safely infer it should be using as the second type parameter for CustomStringType? Remember: you can only make logical assumptions that the compiler can make, no cheating and using your domain knowledge to resolve the issue! On the other hand, if you flip it and provide just the TransactionStatus type, secretly hoping that reflection will somehow solve your problems, it might be possible that two different classes both implement IStringToTypeConverter<TransactionStatus>. You've still got a problem, you don't know which one is correct for your prob

Categories : C#

does Java type erasure erase my generic type?
Some Generic type information is stored in Signature attributes . Refer JLS 4.8 and 4.6 and JVM spec 4.3.4. Read here: Probably the most common complaint about generics in Java is that they are not reified - there is not a way to know at runtime that a List<String> is any different from a List<Long>. I've gotten so used to this that I was quite surprised to run across Neil Gafter's work on Super Type Tokens. It turns out that while the JVM will not track the actual type arguments for instances of a generic class, it does track the actual type arguments for subclasses of generic classes. In other words, while a new ArrayList<String>() is really just a new ArrayList() at runtime, if a class extends ArrayList<String>, then the JVM knows that String is the actual t

Categories : Java

Java type parameter is hiding a generic type?
Try this: public abstract class BaseWidgetProcessor<COMMAND> { protected Widget<COMMAND> widget; public BaseWidgetProcessor(Widget<COMMAND> widget) { this.widget = widget; } // presumably uses widget public abstract COMMAND process(); }

Categories : Java

Determining if type is a subclass of a generic type
Something like this should work. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { Check(new Foo()); Check(new Bar()); Console.ReadLine(); } static void Check<T>(T obj) { // "The type T cannot be used as type parameter..." if (IsDerivedOfGenericType(typeof(T), typeof(Entity<>))) { System.Console.WriteLine(string.Format("{0} is Entity<T>", typeof(T))); } } static bool IsDerivedOfGenericType(Type type, Type genericType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)

Categories : C#

c# Generic type and real type associations
You should be using an object to hold the data and a Type object to hold the type of the data stored, like bellow: public Type Type { get; set; } public Object Value { get; set; } if (Type == typeof (int)) { int realValue = (int) Value; } if (Type == typeof(string)) { string RealValue; Buffer.Blockcopy(RealValue, 0, Value, 0, MetadataSizeInValues*sizeof (char)); } if (Type == typeof(float)) { float RealValue = (float) Value; }

Categories : C#

Comparing the run-time type of a generic type
I suspect prop.PropertyType is actually ObjectSet<X> for some X. You probably want something like: if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(ObjectSet<>))

Categories : C#

Collection of a Type using a Generic Type of any kind
Simple approach Just add another interface that is not generic: public interface IServiceInvokerUntyped { } public interface IServiceInvoker<TServiceContract> : IServiceInvokerUntyped { } Declare the dictionary it like this: private Dictionary<string, IServiceInvokerUntyped> _serviceInvocationCollection = new Dictionary<string, IServiceInvokerUntyped>(); Variant approach If your generic type parameter can be declared as covariant: public interface IServiceInvoker<out T> : IServiceInvokerUntyped { } Declare the dictionary it like this: private Dictionary<string, IServiceInvoker<object>> _serviceInvocationCollection = new Dictionary<string, IServiceInvoker<object>>(); For contravariance, just change 'out' to 'in' and modify the

Categories : C#

Linkage error:Loader Constraint violation: previously initiated loading for a different type with name "org/w3c/dom/Type Info"
This happened to me with the JMX MBeanServer class. Groovy was loading one of them with its classloader and so was the JVM. In your case it sounds like the TypeInfo class exists in rt.jar just fine, but another class loader loads it from that jar (or another jar) again. Running the JRE with "-verbose:class" showed that double load behavior. Then I moved the offending jar out of my classpath and it worked just fine with the one loaded by Groovy. I would recommend moving rt.jar out of your classpath, or if you need other classes inside of rt.jar try unjaring and rejaring it without the Type class. That way the classloaders will be forced to use the ones in xmlbeans-2.5.0.jar or xbean-2.1.0.jar.

Categories : Misc

How To Cast Generic List of One Type To Generic List of an Unknown Type
If you know that each item in the list is of type ObjectType, you can do this: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<int> resultList = sourceList.Cast<int>().ToList(); If you actually want to convert each item in the list in a generic way, the simplest way would be to do something like this: public static IEnumerable<T> ConvertTo<T>(this IEnumerable items) { return items.Cast<object>().Select(x => (T)Convert.ChangeType(x, typeof(T))); } This would be implemented as an extension method, so you can write: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<string> resultList = sourceList.ConvertTo<string>().ToList(); If the target type isn't known at compile-time, you would i

Categories : C#

Generic Type x Generic Parameter: Building a "very generic" structure
Well, first of all, you're overcomplicating this. All you really need to do is: public void add(final Tree<? extends T> subTree) { Theres no need to parameterize add(). But anyways, I'll address your original attempt: You want SubTree extends Tree<Leaf>, because even if Leaf extends T you can't guarantee that SubTree extends Tree<T> with SubTree<Leaf> matches. E.g. if your class hierarchy is: public class Base { } public class A extends Base { } public class B extends Base { } If Leaf is A and SubTree is Tree<B> then add (final SubTree<Leaf>) does not match Tree<B>. So conceptually you actually want this: public <Leaf extends T, SubTree extends Tree<Leaf>> void add(final SubTree<Leaf> subTree) { Of course that is not va

Categories : Java

Generic type constraint on generic type
That's not possible. You have to include TChannel as a generic type parameter of Proxy. One of the options to get over this “limitation” (in quotes because it is a by-design feature that arises from how the C# type system works) is to use an interface which each channel would be supposed to implement: public interface IChannel { … } public class Proxy<TClient>() where TClient : ClientBase<IChannel> { } public class MyObscureChannel : IChannel { … } public class MyObscureClient : ChannelBase<MyObscureChannel> { … } … var client = new Proxy<MyObscureClient>(…); // MyObscureChannel is implied here

Categories : C#

Unable to cast object of type 'System.Linq.OrderedEnumerable`2[***]' to type 'System.Collections.Generic.IEnumerable`1[***]'
You're trying to convert a collection of DirectoryToken to a collection of Token. This is called a covariant conversion, and it's only supported in .Net 4.0 or later. If you can't upgrade, you can call .Cast<Token>() to create a new IEnumerable<T> instance (actually an iterator) that casts each object to the desired type. Under no circumstances do you need an explicit cast operation.

Categories : C#

Typescript Error Message error TS2173: Generic type references must include all type arguments
That line should have been: promise(type?: any, target?: any): JQueryPromise<any>; I'll send them a pull request. Thanks. JQueryPromise is a generic interface. i.e. it takes type parameters. Starting with TS 0.9.1.1 they are more strict about generic parameters. They must be specified from now on. This was allowed in previous versions (where the type was assumed to any implicitly) but the compiler analysis is stricter now (and the type must be specified explicitly).

Categories : Typescript

Passing a class with type parameter as type parameter for generic method in Java
This is actually possible in Java, using some "tricks". Don't succumb to pressure from the C# fanatics! (j/k) The "trick" is to create a class that extends a generic type, and access the value of the type parameter of the parent class through the Type returned by .getGenericSuperclass() or .getGenericInterfaces(). This is quite cumbersome. To simplify our lives, Google has already written most of the boring part of the code for us, and made it available through Guava. Check the TypeToken class, which does exactly what you want. For example: TypeToken<List<String>> stringListTok = new TypeToken<List<String>>() {}; Then you pass around a TypeToken<T> instead of a Class<T> and that's all. It provides you with methods to do reflection on the type repre

Categories : Java

return generic IEnumerable when passing concrete type parameter for a generic method
You cannot convert the Type class to a generic T parameter without using reflection. The parameter also needs to be present as part of the method. Jon Skeet was using type inference by example combined with generics in order to guarantee type safety and simplify the generic code. Unfortunately you will lose that type safety using Type and reflection. private IEnumerable<EntityObject> GetFilteredData(Type entityType, SortedList<string, string> filterList, List<int> weeks) { var method = typeof(<class>).GetMethod("GetFilteredDataImpl"); var generic = method.MakeGenericMethod(entityType); return (IEnumerable<EntityObject>)generic.Invoke(this, new[] {

Categories : C#

How to realize explicit and implicit type conversion for non-generic synonyms of generic struct?
The error User-defined conversion must convert to or from the enclosing type. means that your conversion operators need to convert to/from A<T>. Yours are converting to/from A<int/string>. That's not the same thing (much less general at least). So this cannot work. You have to find some other way to do the conversions. Maybe runtime casting can help here (define the operators as acting on A<T> and do casting inside of them). I think this problem is unrelated to the type synonyms. In fact they made the question harder to understand.

Categories : C#

Late-Binding Exception Calling Generic Method of Generic Type in C#
Your GetFirstGenericArgument() is wrong. Calling GetGenericTypeDefinition() returns the underlying open generic type. Its type argument is T. Instead, you should write t.GetGenericArguments()[0], which will get the value of the generic type parameter for the closed type. No; your code doesn't make any sense. What on earth are you trying to do? I suspect that you actually want to write public class CollectionHandler<T> { public void Handle(IEnumerable<T> collection) { // Look ma, no reflection! } }

Categories : C#

How to declare a const field of a generic value type provided as generic argument
Type parameter is not allowed for constant type. Because a struct cannot be made const (from C# specification 10.4 Constants) The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. A kind of workaround to this limitation is to declare it as static readonly. public static readonly ValueType val = default(ValueType);

Categories : C#

Reflection - Navigate a non-generic method from a generic type definition to a concrete one
You can use the MakeGenericType method, like this: m.DeclaringType.MakeGenericType(typeof(int)) and then probably GetMethod again if you really want to go this way: m.DeclaringType.MakeGenericType(typeof(int)).GetMethod("Method"); However, consider Jon Skeet's comment for simpler solution.

Categories : C#

How can i make a generic function of two functions with a generic type specifier to a parameter
public class BinarySearchComparers<T> : IComparer<KeyValuePair<int, T>> // Declares a generic type { public int Compare(KeyValuePair<int, T> x, KeyValuePair<int, T> y) { return x.Key.CompareTo(y.Key); } } Is it what you want? Update Given Chris Sinclair understanding of your question, the solution might be: public class BinarySearchComparers<U, T> : IComparer<KeyValuePair<U, T>> // Declares a generic type where U : IComparable<U> // Restricts the type U to implémentations of IComparable<U> (necessary to call CompareTo) { public int Compare(KeyValuePair<U, T> x, KeyValuePair<U, T> y) { return x.Key.CompareTo(y.Key); } }

Categories : C#



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