w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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#

C# generic constraint for Type to be castable
Types are determined during compilation. You can't change the types during runtime. It is possible to cast object to its base or child class Ref - Difference between object a = new Dog() vs Dog a = new Dog()

Categories : C#

Generic type attribute with OR constraint
There is no or. What you probably want to do is this: interface IKeyValue<TKey, TValue> { public TKey Key {get;set;} public TValue Value {get;set;} } public class Attribute : IKeyValue<string, string> { public override string ToString() { return String.Format("{0}={1}:{2}", Constants.ATTRIBUTE_CHAR, Key, Value); } } public class BoolAttribute : IKeyValue<string, bool> { public override string ToString() { return Value ? String.Format("{0}={1}", Constants.ATTRIBUTE_CHAR, Key) : String.Empty; } }

Categories : C#

Casting generic type with interface constraint
Wrapper<Foo> needs to be Wrapper<IFoo>. Then you should be able to cast it. And it needs to implement the interface too. The cast below works... I don't think you can cast an objects generic type parameter to a different type (i.e. IWrapper<Foo> to IWrapper<IFoo>). void Main() { var foo = new Wrapper(); var t = foo as IWrapper<IFoo>; t.Dump(); } public interface IFoo {} public class Foo : IFoo {} public interface IWrapper<T> where T : IFoo {} public class Wrapper : IWrapper<IFoo> {}

Categories : C#

Generic inference of type parameter with constraint to other type parameter
You can't infer just some type parameters within a method call. Generic type inference either infers all type parameters, or none. There's no way of inferring THost from the parameters (there could be multiple classes which derive from HostBase<Config>), which means you basically can't use type inference for that method. Looking at this specific example, I think you're going to find it tricky to use type inference at all, because of the way the relationships work.

Categories : C#

Can you enforce the same constraint on multiple generic type parameters?
No, that is not supported. The C# language spec states Each type-parameter-constraint-clause consists of the token where, followed by the name of a type parameter, followed by a colon and the list of constraints for that type parameter. The key here is a, indicating that the grammer requires where <TypeParam> : <Constraint1>,<Constraint2>, etc.. .

Categories : C#

How can I cast an object as an interface which is a generic type constraint in Delphi
Since T can be anything you must make it clear to Delphi that T will be an interface. Since all interfaces inherit from IUnknown, you can write this: Web = class class function Proxy<T :IUnknown>(svc : string) : T; end;

Categories : Delphi

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#

JSON Schema: represent constraint to encode object type in string type
I agree, either you choose the object or string type. I have looked into the JSON Schema documentation and I could not find anything to express the constraint as clear as needed. Hence, a short discussions of the two approaches there are to my mind. Type String JSON Schema defines seven primitive types, including object. A string is simply defined as a JSON string. The RFC 4627 defines a JSON string as follows A string is a sequence of zero or more Unicode characters This would apply to your case, even though the content of the string has to be restricted. The question is how to communicate the restriction. I would use a description to reference to another subschema. You can even define a pattern for the string an encode the subschema as regular expression. This, however,

Categories : Javascript

Why does a generic type constraint result in a no implicit reference conversion error?
Because you declared your MyAppointment class using the concrete type rather than the interface. You should declare as follows: class MyAppointment : Appointment<IAppointmentProperties> { } Now the conversion can occur implicitly. By declaring AppointmentEntry<T> with the constraint where T: IAppointment<IAppointmentProperties> you are creating a contract whereby the unspecified type for AppointmentEntry<T> must accommodate any type that is declared with IAppointmentProperties. By declaring the type with the concrete class you have violated that contract (it implements a type of IAppointmentProperties but not any type).

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

Return statement not satisfying generic return type despite the constraint?
Execute is supposed to return a TOutput but instead it's returning a List of TOutputType. A TOutput is constrained to be a List<TOutputType> but a List<TOutputType> isn't constrained to be a TOutput. Try instantiating result as: var result = new TOutput(); and see how that goes.

Categories : C#

Cant declare an instance with type parameter that is one layer off the constraint of the type parameter
Since TypedTableBase is generic, when you use it, you have to specify the actual datatype as in public class A<T> where T:DataTable { } public class B :TypedTableBase<DataRow> { } class MyClass { A<B> asdf = new A<B>(); }

Categories : C#

Type 'MyClass' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute. Consider marking the base type
One approach would be to override it: public new byte[] SomeByteArray { get; set; } and then you could ignore it with the IgnoreDataMember attribute.

Categories : C#

Entity Framework 5 table-per-type update, change sub type but keep same base type
I don't have a good answer, but I can think of four "solutions" that are really workarounds: Don't use DBMS-computed values for your primary keys (if you already use natural keys, it's fine). Use DBMS-computed surrogate keys. Follow something like the state pattern. Do some evil voodoo with the object state manager. Update: There seems to be a popular consensus that trying isn't even worth it; most people thus simply use stored procedures instead to work around the problem. Changing Inherited Types in Entity Framework Entity Framework: Inheritance, change object type Changing the type of an (Entity Framework) entity that is part of an inheritance hierarchy Changing the type of an entity that is part of an inheritance hierarchy Using natural keys First, remember that the objects tr

Categories : Entity Framework

A shorter type constraint for F#
Ok, found it. I was browsing through the examples in MSDN's F# type constraint and at the thrid from the last example, I found this let inline add(value1 : ^T when ^T : (static member (+) : ^T * ^T -> ^T), value2: ^T) = value1 + value2 I notice that constraint for ^T in value1 is used in value2, so I change my cmp function to this let cmp (x: 'a when 'a :> 'a System.IComparable) (y: 'a) = x.CompareTo(y) I ran through the fsi and got the same type signature > let cmp (x: 'a when 'a :> 'a System.IComparable) (y: 'a) = x.CompareTo(y);; val cmp : 'a -> 'a -> int when 'a :> System.IComparable<'a> > let cmp (x: 'a when 'a :> 'a System.IComparable) (y: 'a when 'a :> 'a System.IComparable) = x.CompareTo(y);; val cmp : 'a -> 'a -> int when 'a

Categories : F#

c#type constraint multiple possibilty?
It's not possible. How would you differentiate between one type or the other inside the function? Even then, you'd probably have to do a type check and specialize, which defeats the purpose of generic method. If you have two distinct possibilities, it would be the easiest to provide two specialized overloads: public void ParseXml(string val) public void ParseXml(XElement element) And possibly the generic version for any other type, if it makes sense.

Categories : C#

Validator for MethodArgumentNotValidException only handles constraint of same type
Nothing is wrong the validator for @Size and @Pattern by default accept null as valid. So you actually need both annotations (@NotNull and @Pattern/@Size). These annotations only trigger validation of values which are non-null, these validations don't imply that null values are invalid that is where the @NotNull is for. This is assuming you are using hibernate-vaildator (as that is the out-of-the-box supported validator).

Categories : Java

Functor instance for a GADT with type constraint
You can do this using a CoYoneda functor. The idea is simple: have an additional functional field where you accumulate your fmaping functions. When you decode your value, then apply that function. Here's the code: {-# LANGUAGE GADTs #-} import Data.ByteString.Char8 import Data.Serialize data Serialized a where MkSerialized :: (Serialize a) => ByteString -> (a -> b) -> Serialized b decode' :: Serialized a -> a decode' (MkSerialized bs f) = let Right r = decode bs in f r instance Functor Serialized where fmap f (MkSerialized bs g) = MkSerialized bs (f . g) This also has the benefit of automatically fusing multiple fmaps instead of repeated decodings and encodings, as would be in your case.

Categories : Haskell

breezejs: adding referential constraint to an entity type
So you are getting meta data but it doesn't have a relationship between the entities. Hmm I have not gotten metaData AND tried to create additional model properties that are related. Your best bet is to add a property that is a navigation type on the constructor. http://www.breezejs.com/sites/all/apidocs/classes/EntityType.html#method_addProperty If it were me, I would try it this way (or something similar) inside of the constructor - myEntity.addProperty({ associatedEntity: { entityTypeName: "AssociatedEntity", isScalar: true, associationName: "AssociatedEntity_MyEntitys", foreignKeyNames: ["associatedEntityId"] } }); Where myEntity is the name of the current entity, AssociatedEntity would be y

Categories : Javascript

GenericArguments[1], 'T', on 'BinaryNode`2[N,T]' violates the constraint of type parameter 'T'
I managed to get a repro case as simple as: public class Node<T> : Node<Node<T>, T> where T : IComparable { } abstract public class Node<N, T> where N : Node<N, T>, new() where T : IComparable { } I noticed that the error message that was being thrown though was in my test cs project, and not the cs project that the Node class was in. However, there was no line or file associated with the error. If I excluded my test project from the solution though, the solution built successfully. I don't know why this was the case, but I finally tried excluding the test project's automatically generated folder "Test References", which had a DataStructures.accessor file in it. Excluding the file seemed to fix the issue.

Categories : C#

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#

Type constraints for automatic function constraint deduction in Haskell
Well, the issue is that this constraint applies to the constructor, not to the datatype as a whole. That's why DatatypeContexts are actually almost useless… You can read more about it here. If you were hoping that the second paragraph contains a solution, then you are out of luck, unfortunatelly. I'm not aware of such a solution, and it seems that it indeed does not exist. The wiki article mentions usage of MultiParamTypeClasses instead, but that's not as convenient, honestly.

Categories : Haskell

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#

Play source file "Reads.scala" use of generalized type constraint
This is because this type witness is also a function. It is declared in Predef as: sealed abstract class <:<[-From, +To] extends (From => To) with Serializable So A <:< JsValue is also a function (A) => JsValue. You might wonder what the function does: it does nothing, it takes an A and directly returns it (as a JsValue). To see why this is useful consider this example: sealed trait Root { def bip() { println("bip") } } def makeBip[A <: Root](a: A) { a.bip() // works because a is known to the type system to be a Root } def makeBip2[A](a: A)(implicit ev: A <:< Root) { a.bip() // works, because implicit resolution turns it into `ev(a).bip()` } The last method makeBip2 would not compile without the implicit because even though you know that a is a Root

Categories : Scala

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#

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#

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#

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#

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 prevent type from being used as a member variable type in a struct/class?
If you can use an object outside of a class, it can be a member of a class. I'm 99.9% sure that you can't stop that in any way (that doesn't restrict how/where you can use T in other ways - clearly having a private constructor would prevent it from being a direct member of a class, but it would also restrict it from being used in the other three scenarios you are showing).

Categories : C++

C2011: 'struct' type redefinition and C2027: use of undefined type
In your types.h file you should have something like this: #ifndef TYPES_H #define TYPES_H struct ... #endif This will prevent the compiler from parsing the include file mulitple times if you include it more than once, which would cause multiple definitions. The name itself doesn't matter, but you should make sure that it is unique and not defined by some other include file as well.

Categories : C++

Does a variable of an interface type act as value type if the underlying implementation is a struct?
No, interface is a contract, to make it work properly you need to use ref keyword. public void SetInterfaceProp(ref IMyInterface thingy) { thingy.desc = "the implementing type is a struct"; } What matters here is a real type that stays inside that interface wrap. To be more clear: even if code with method SetInterfaceProp defined like public void SetInterfaceProp(IMyInterface thingy) { thingy.desc = "the implementing type is a struct"; } will work: IMyInterface inter= default(MyStruct); SetInterfaceProp(inter); this one will not : MyStruct inter = default(MyStruct); SetInterfaceProp(inter); You can not gurantee that the caller of your method will always use IMyInterface, so to guarantee expected behavior, in this case, you can define ref keyword, that will guaran

Categories : C#

Entity Framework Code First Table-Per-Type Inheritance include base type
The answer was to remove the abstract keyword from the Base class (Person): FROM: public abstract class Person { public string FirstName { get; set; } public string LastName { get; set; } public Training Training { get; set; } } TO: public class Person { public string FirstName { get; set; } public string LastName { get; set; } public Training Training { get; set; } }

Categories : C#

Capture Return Value of Method returning base type or derived type
Well, you can do if (ref instanceof B) { B r = (B)ref; } but fundamentally I think you have a modelling problem. Why do you have a factory (or similar) returning instances of A or B, and then have to determine what you've been given ? Perhaps you can have a method common to but implemented differently in both A and B, and call that, passing in your reference to the caller (originating) class. That way you can invoke a different method depending on both the type calling, and the type being called.

Categories : Java

Output of static base type and dynamic derived type
Have a look at Can virtual functions have default parameters?: A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides. Therefore, bptr->display(); calls the derived version of display, but uses the argument from base, the static type of the pointer bptr. This is because the default value of an argument has to be determined at compile time while dynamic binding is deferred to the runtime. Using different default arguments in the base and derived versions of the same virtual is almost guaranteed to cause trouble. Problems are likely to arise whe

Categories : C++

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

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 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

.NET LINQ to Entities base where clause for generic Type
I think LINQ to Entities does not know how to match the cast operator to SQL request. As a suggestion, you could try something like that: IEnumerable<IPublishable> ReadPublishable(Expression<Func<DomainModelType, bool>> condition) The expression act as a predicate. So you pass to the ReadPublishable function a predicate that filters the IPublishable objects you need. I tried successfully but only on simple predicates so, I do not know whether that works if you make use of "is" or "as" operators.

Categories : C#



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