Search Results

Search found 53463 results on 2139 pages for 'net generics'.

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

  • WPF View/ViewModels using Generics- how?

    - by Investor5555
    New to WPF, so please bear with me... Suppose I have 2 tables in SQL Thing OtherThing Both have the exact same fields: ID (int) Name (string) Description (string) IsActive (bit/bool) DateModified (DateTime) So, I want to create one Model (not two) and do something like this: BaseModel<T>() { public int ID {get;set;} ... } etc. (of course, using the INotifyPropertyChanged, just trying to keep the code simple). I want to be able to create a BaseView and BaseViewModel that would work with whatever model conforms to the Thing/OtherThing. I am really at a loss as to what to do here to make this generic, so I don't have to have a ThingView/ThingViewModel and a OtherThingView/OtherThingViewModel... It seems that this should be simple, but I cannot seem to figure it out. Does anyone have a code example where they could interchange various items from a dropdown list using one view, one ViewModel, and one base datamodel (and switching out the type from a dropdown)? For example, a combobox has 3 identical table structures for Thing OtherThing SomeThing and on selection changed, I want to pull the data from whatever table was selected, to be able to do standard CRUD operations on any of these 3 tables, without having to create concrete classes for each view/viewmodel.

    Read the article

  • Java generics SuppressWarnings("unchecked") mystery

    - by Johannes Ernst
    Why does code alternative(1) compile without warnings, and code alternative(2) produce an "unchecked cast" warning? Common for both: class Foo<T> { Foo( T [] arg ) { } } Alternative (1): class Bar<T> extends Foo<T> { protected static final Object [] EMPTY_ARRAY = {}; @SuppressWarnings("unchecked") Bar() { super( (T []) EMPTY_ARRAY ); } } Alternative (2): class Bar<T> extends Foo<T> { @SuppressWarnings("unchecked") Bar() { super( (T []) EMPTY_ARRAY ); } protected static final Object [] EMPTY_ARRAY = {}; } Alternative (2) produces: javac -Xlint:unchecked Foo.java Bar.java Bar.java:4: warning: [unchecked] unchecked cast super( (T []) EMPTY_ARRAY ); ^ required: T[] found: Object[] where T is a type-variable: T extends Object declared in class Bar 1 warning This is: java version "1.7.0_07" Java(TM) SE Runtime Environment (build 1.7.0_07-b10) Java HotSpot(TM) 64-Bit Server VM (build 23.3-b01, mixed mode)

    Read the article

  • Refactoring exercise with generics

    - by Berryl
    I have a variation on a Quantity (Fowler) class that is designed to facilitate conversion between units. The type is declared as: public class QuantityConvertibleUnits<TFactory> where TFactory : ConvertableUnitFactory, new() { ... } In order to do math operations between dissimilar units, I convert the right hand side of the operation to the equivalent Quantity of whatever unit the left hand side is in, and do the math on the amount (which is a double) before creating a new Quantity. Inside the generic Quantity class, I have the following: protected static TQuantity _Add<TQuantity>(TQuantity lhs, TQuantity rhs) where TQuantity : QuantityConvertibleUnits<TFactory>, new() { var toUnit = lhs.ConvertableUnit; var equivalentRhs = _Convert<TQuantity>(rhs.Quantity, toUnit); var newAmount = lhs.Quantity.Amount + equivalentRhs.Quantity.Amount; return _Convert<TQuantity>(new Quantity(newAmount, toUnit.Unit), toUnit); } protected static TQuantity _Subtract<TQuantity>(TQuantity lhs, TQuantity rhs) where TQuantity : QuantityConvertibleUnits<TFactory>, new() { var toUnit = lhs.ConvertableUnit; var equivalentRhs = _Convert<TQuantity>(rhs.Quantity, toUnit); var newAmount = lhs.Quantity.Amount - equivalentRhs.Quantity.Amount; return _Convert<TQuantity>(new Quantity(newAmount, toUnit.Unit), toUnit); } ... same for multiply and also divide I need to get the typing right for a concrete Quantity, so an example of an add op looks like: public static ImperialLengthQuantity operator +(ImperialLengthQuantity lhs, ImperialLengthQuantity rhs) { return _Add(lhs, rhs); } The question is those verbose methods in the Quantity class. The only change between the code is the math operator (+, -, *, etc.) so it seems that there should be a way to refactor them into a common method, but I am just not seeing it. How can I refactor that code? Cheers, Berryl

    Read the article

  • c# Generics problem

    - by UpTheCreek
    Can anyone tell me why this does not work? I would have thought the constraint would make it valid. public class ClassA<T> where T : ICommon { public ClassA() { ClassB b = new b(); IEnumerable<T> alist = new IList<T>; b.items = alist; //Error: cannot convert from IEnumerable<T> to IEnumerable<ICommon>' } } public class ClassB { IEnumerable<ICommon> items { get; set;} .... }

    Read the article

  • C# Fun with Generics - Mutual Dependencies

    - by Kenneth Cochran
    As an experiment I'm trying to write a generic MVP framework. I started with: public interface IPresenter<TView> where TView: IView<IPresenter<... { TView View { get; set;} } public interface IView<TPresenter> where TPresenter:IPresenter<IView<... { TPresenter Presenter { get; set; } } Obviously this can't work because the types of TView and TPresenter can't be resolved. You'd be writing Type<Type<... forever. So my next attempt looked like this: public interface IView<T> where T:IPresenter { ... } public interface IView:IView<IPresenter> { } public interface IPresenter<TView> where TView: IView { ... } public interface IPresenter: IPresenter<IView> { ... } This actually compiles and you can even inherit from these interfaces like so: public class MyView : IView, IView<MyPresenter> { ... } public class MyPresenter : IPresenter, IPresenter<MyView> { ... } The problem is in the class definition you have to define any members declared in the generic type twice. Not ideal but it still compiles. The problem's start creeping up when you actually try to access the members of a Presenter from a View or vice versa. You get an Ambiguous reference when you try to compile. Is there any way to avoid this double implementation of a member when you inherit from both interfaces? Is it even possible to resolve two mutually dependent generic types at compile time?

    Read the article

  • With this generics code why am I getting "Argument 1: cannot convert from 'ToplogyLibrary.Relationsh

    - by Greg
    Hi, Any see why I'm getting a "Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase' to 'TRelationship'" in the code below, in CreateRelationship() ? public class TopologyBase<TKey, TNode, TRelationship> where TNode : NodeBase<TKey>, new() where TRelationship : RelationshipBase<TKey>, new() { // Properties public Dictionary<TKey, TNode> Nodes { get; private set; } public List<TRelationship> Relationships { get; private set; } // Constructors protected TopologyBase() { Nodes = new Dictionary<TKey, TNode>(); Relationships = new List<TRelationship>(); } // Methods public TNode CreateNode(TKey key) { var node = new TNode {Key = key}; Nodes.Add(node.Key, node); return node; } public void CreateRelationship(TNode parent, TNode child) { // Validation if (!Nodes.ContainsKey(parent.Key) || !Nodes.ContainsKey(child.Key)) { throw new ApplicationException("Can not create relationship as either parent or child was not in the graph: Parent:" + parent.Key + ", Child:" + child.Key); } // Add Relationship var r = new RelationshipBase<TNode>(); r.Parent = parent; r.Child = child; Relationships.Add(r); // *** HERE *** "Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase<TNode>' to 'TRelationship'" } } public class RelationshipBase<TNode> { public TNode Parent { get; set; } public TNode Child { get; set; } } public class NodeBase<T> { public T Key { get; set; } public NodeBase() { } public NodeBase(T key) { Key = key; } }

    Read the article

  • JAVA Inheritance Generics and Casting.

    - by James Moore
    Hello, I have two classes which both extends Example. public class ClassA extends Example { public ClassA() { super("a", "class"); } .... } public class ClassB extends Example { public ClassB() { super("b", "class"); } .... } public class Example () { public String get(String x, String y) { return "Hello"; } } So thats all very well. So suppose we have another class called ExampleManager. With example manager I want to use a generic type and consequently return that generic type. e.g. public class ExampleManager<T extends Example> { public T getExample() { return new T("example","example"); // So what exactly goes here? } } So where I am returning my generic type how do i get this to actually work correctly and cast Example as either classA or classB? Many Thanks

    Read the article

  • Using generics in F# to create an EnumArray type

    - by Matthew
    I've created an F# class to represent an array that allocates one element for each value of a specific enum. I'm using an explicit constructor that creates a dictionary from enum values to array indices, and an Item property so that you can write expressions like: let my_array = new EnumArray<EnumType, int> my_array.[EnumType.enum_value] <- 5 However, I'm getting the following obscure compilation error at the line marked with '// FS0670' below. error FS0670: This code is not sufficiently generic. The type variable ^e when ^e : enum<int> and ^e : equality and ^e : (static member op_Explicit : ^e -> int) could not be generalized because it would escape its scope. I'm at a loss - can anyone explain this error? type EnumArray< 'e, 'v when 'e : enum<int> and 'e : equality and ^e : (static member op_Explicit : ^e -> int) > = val enum_to_int : Dictionary<'e, int> val a : 'v array new() as this = { enum_to_int = new Dictionary<'e, int>() a = Array.zeroCreate (Enum.GetValues(typeof<'e>).Length) } then for (e : obj) in Enum.GetValues(typeof<'e>) do this.enum_to_int.Add(e :?> 'e, int(e :?> 'e)) member this.Item with get (idx : 'e) : 'v = this.a.[this.enum_to_int.[idx]] // FS0670 and set (idx : 'e) (c : 'v) = this.a.[this.enum_to_int.[idx]] <- c

    Read the article

  • C# generics method invocation

    - by Firat KÜÇÜK
    Hi, i have some polymorphic methods and i want to call via using an intermediate method. Following class is the simplified version of my program. class Program { public class A { } public class B { } public class C { } public void SomeMethod(A value) { Console.WriteLine("A value"); } public void SomeMethod(B value) { Console.WriteLine("B value"); } public void SomeMethod(C value) { Console.WriteLine("C value"); } static void Main(string[] args) { Program p = new Program(); // code block p.IntermediateMethod<A>(new A()); p.IntermediateMethod<B>(new B()); p.IntermediateMethod<C>(new C()); } public void IntermediateMethod<T>(T value) { // code block SomeMethod(value); // code block } }

    Read the article

  • Java Generics Class Parameter Type Inference

    - by Pindatjuh
    Given the interface: public interface BasedOnOther<T, U extends BasedList<T>> { public T getOther(); public void staticStatisfied(final U list); } The BasedOnOther<T, U extends BasedList<T>> looks very ugly in my use-cases. It is because the T type parameter is already defined in the BasedList<T> part, so the "uglyness" comes from that T needs to be typed twice. Problem: is it possible to let the Java compiler infer the generic T type from BasedList<T> in a generic class/interface definition? Ultimately, I'd like to use the interface like: class X implements BasedOnOther<BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } } // Does not compile, due to invalid parameter count. Instead: class X implements BasedOnOther<SomeType, BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } }

    Read the article

  • C# Pass Generics At Runtime

    - by TheCloudlessSky
    I have a method like the following: public IEnumerable<T> GetControls<T>() : where T : ControlBase { // removed. } I then created a class: public class HandleBase<TOwner> : ControlBase : TOwner { // Removed } I'd like to be able to call GetControls<HandleBase<this.GetType()>>; where it would use the type of THIS class to pass to the HandleBase. This would in essentially get all HandleBase that have an owner of THIS type. How can I achieve this?

    Read the article

  • Java generics: Illegal forward reference

    - by Arian
    Given a generic interface interface Foo<A, B> { } I want to write an implementation that requires A to be a subclass of B. So I want to do class Bar<A, B super A> implements Foo<A, B> { } // --> Syntax error or class Bar<A extends B, B> implements Foo<A, B> { } // --> illegal forward reference But the only solution that seems to work is this: class Bar<B, A extends B> implements Foo<A, B> { } which is kind of ugly, because it reverses the order of the generic parameters. Are there any solutions or workarounds to this problem?

    Read the article

  • Circular dependency with generics

    - by devoured elysium
    I have defined the following interface: public interface IStateSpace<State, Action> where State : IState where Action : IAction<State, Action> // <-- this is the line that bothers me { void SetValueAt(State state, Action action); Action GetValueAt(State state); } Basically, an IStateSpace interface should be something like a chess board, and in each position of the chess board you have a set of possible movements to do. Those movements here are called IActions. I have defined this interface this way so I can accommodate for different implementations: I can then define concrete classes that implement 2D matrix, 3D matrix, graphs, etc. public interface IAction<State, Action> { IStateSpace<State, Action> StateSpace { get; } } An IAction, would be to move up(this is, if in (2, 2) move to (2, 1)), move down, etc. Now, I'll want that each action has access to a StateSpace so it can do some checking logic. Is this implementation correct? Or is this a bad case of a circular dependence? If yes, how to accomplish "the same" in a different way? Thanks

    Read the article

  • Problem at JUnit test with generics

    - by Tom Brito
    In my utility method: public static <T> T getField(Object obj, Class c, String fieldName) { try { Field field = c.getDeclaredField(fieldName); field.setAccessible(true); return (T) field.get(obj); } catch (Exception e) { e.printStackTrace(); fail(); return null; } } The line return (T) field.get(obj); gives the warning "Type safety: Unchecked cast from Object to T"; but I cannot perform instanceof check against type parameter T, so what am I suppose to do here?

    Read the article

  • Java Generics Class Type Parameter Inference

    - by Pindatjuh
    Given the interface: public interface BasedOnOther<T, U extends BasedList<T>> { public T getOther(); public void staticStatisfied(final U list); } The BasedOnOther<T, U extends BasedList<T>> looks very ugly in my use-cases. It is because the T type parameter is already defined in the BasedList<T> part, so the "uglyness" comes from that T needs to be typed twice. Problem: is it possible to let the Java compiler infer the generic T type from BasedList<T> in a generic class/interface definition? Ultimately, I'd like to use the interface like: class X extends BasedOnOther<BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } } Instead: class X extends BasedOnOther<SomeType, BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } }

    Read the article

  • Performance of C# method polymorphism with generics

    - by zildjohn01
    I noticed in C#, unlike C++, you can combine virtual and generic methods. For example: using System.Diagnostics; class Base { public virtual void Concrete() {Debug.WriteLine("base concrete");} public virtual void Generic<T>() {Debug.WriteLine("base generic");} } class Derived : Base { public override void Concrete() {Debug.WriteLine("derived concrete");} public override void Generic<T>() {Debug.WriteLine("derived generic");} } class App { static void Main() { Base x = new Derived(); x.Concrete(); x.Generic<PerformanceCounter>(); } } Given that any number of versions of Generic<T> could be instantiated, it doesn't look like the standard vtbl approach could be used to resolve method calls, and in fact it's not. Here's the generated code: x.Concrete(); mov ecx,dword ptr [ebp-8] mov eax,dword ptr [ecx] call dword ptr [eax+38h] x.Generic<PerformanceCounter>(); push 989A38h mov ecx,dword ptr [ebp-8] mov edx,989914h call 76A874F1 mov dword ptr [ebp-4],eax mov ecx,dword ptr [ebp-8] call dword ptr [ebp-4] The extra code appears to be looking up a dynamic vtbl according to the generic parameters, and then calling into it. Has anyone written about the specifics of this implementation? How well does it perform compared to the non-generic case?

    Read the article

  • C# Generics Question

    - by TheCloudlessSky
    Would it be possible to do something like the following in c#? Basically TParent and TChildren should be types of the class A but not necessairly have the same types that were passed in. I know this may sound confusing but I want to strongly type the children and parents of a particular object, but at the same time they must be of the same type. Because TParent inherits from A this would imply that it requires type parameters that inherit from A but using potentially different types. public class A<TParent, TChildren> where TParent : A where TControls : A { TParent Parent; List<TChildren> Children; } or more easily seen here: public class A<TParent, TChildren> where TParent : A<?, ?> where TChildren : A<?, ?> { TParent Parent; List<TChildren> Children; } I hope this isn't too confusing. Is this at all possible? Thanks :)

    Read the article

  • Java reflection for generics

    - by Vijay Bhore
    I am using Java Reflection to expose methods in custom eclipse tool. I am writing method getReturnType which accepts java.lang.reflect.Method as input and returns object of Class private static Class<?> getReturnType(Method method) { Type type = ((ParameterizedType)method.getGenericReturnType()).getRawType(); return getClass(type); } This code compiles well but at runtime i get the below exception while casting Type to ParameterizedType. java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType Please suggest. Thanks!

    Read the article

  • Java generics question

    - by user247866
    So I have 3 classes. Abstract class A Class B extends class A independent Class C In class D that contains the main method, I create a list of instances of class B List<B> b = methodCall(); // the method returns a list of instances of class B Now in class C I have one method that is common to both A and B, and hence I don't want to duplicate it. I want to have one method that takes as input an instance of class A, as follows: public void someMethod(List<A> a) However, when I do: C c = new C(); c.someMethod(b); I get an error that some-method is not applicable for the argument List<B>, instead it's expecting to get List<A>. Is there a good way to fix this problem? Many thanks!

    Read the article

  • Extension method return using generics

    - by Steven de Salas
    Is it possible to return a generic type using extension methods? For example, I have the following method: // Convenience method to obtain a field within a row (as a double type) public static double GetDouble(this DataRow row, string field) { if (row != null && row.Table.Columns.Contains(field)) { object value = row[field]; if (value != null && value != DBNull.Value) return Convert.ToDouble(value); } return 0; } This is currently used as follows: double value = row.GetDouble("tangible-equity"); but I would like to use the following code: double value = row.Get<double>("tangible-equity"); Is this possible and if so, what would the method look like?

    Read the article

  • Generics Type issue

    - by JohnJohnGa
    ArrayList<Integer> arrI = new ArrayList<Integer>(); ArrayList arrO = arrI; // Warning /* It is ok to add a String as it is an ArrayList of Objects but the JVM will know the real type, arrO is an arrayList of Integer... */ arrO.add("Hello"); /* How I can get a String in an ArrayList<Integer> ?? Even if the compiler told me that I will get an Integer! */ System.out.println(arrI.get(0)); Anybody can explain what's happening here?

    Read the article

  • Creating dynamic generics at runtime using Reflection

    - by MPhlegmatic
    I'm trying to convert a Dictionary< dynamic, dynamic to a statically-typed one by examining the types of the keys and values and creating a new Dictionary of the appropriate types using Reflection. If I know the key and value types, I can do the following: Type dictType = typeof(Dictionary<,>); newDict = Activator.CreateInstance(dictType.MakeGenericType(new Type[] { keyType, valueType })); However, I may need to create, for example, a Dictionary< MyKeyType, dynamic if the values are not all of the same type, and I can't figure out how to specify the dynamic type, since typeof(dynamic) isn't viable. How would I go about doing this, and/or is there a simpler way to accomplish what I'm trying to do?

    Read the article

  • Is It possible to use the second part of this code for repository patterns and generics

    - by newToCSharp
    Is there any issues in using version 2,to get the same results as version 1. Or is this just bad coding. Any Ideas public class Customer { public int CustomerID { get; set; } public string EmailAddress { get; set; } int Age { get; set; } } public interface ICustomer { void AddNewCustomer(Customer Customer); void AddNewCustomer(string EmailAddress, int Age); void RemoveCustomer(Customer Customer); } public class BALCustomer { private readonly ICustomer dalCustomer; public BALCustomer(ICustomer dalCustomer) { this.dalCustomer = dalCustomer; } public void Add_A_New_Customer(Customer Customer) { dalCustomer.AddNewCustomer(Customer); } public void Remove_A_Existing_Customer(Customer Customer) { dalCustomer.RemoveCustomer(Customer); } } public class CustomerDataAccess : ICustomer { public void AddNewCustomer(Customer Customer) { // MAKE DB CONNECTION AND EXECUTE throw new NotImplementedException(); } public void AddNewCustomer(string EmailAddress, int Age) { // MAKE DB CONNECTION AND EXECUTE throw new NotImplementedException(); } public void RemoveCustomer(Customer Customer) { // MAKE DB CONNECTION AND EXECUTE throw new NotImplementedException(); } } // VERSION 2 public class Customer_New : DataRespository<CustomerDataAccess> { public int CustomerID { get; set; } public string EmailAddress { get; set; } public int Age { get; set; } } public class DataRespository<T> where T:class,new() { private T item = new T(); public T Execute { get { return item; } set { item = value; } } public void Update() { //TO BE CODED } public void Save() { //TO BE CODED } public void Remove() { //TO BE CODED } } class Program { static void Main(string[] args) { Customer_New cus = new Customer_New() { Age = 10, EmailAddress = "[email protected]" }; cus.Save(); cus.Execute.RemoveCustomer(new Customer()); // Repository Version Customer customer = new Customer() { EmailAddress = "[email protected]", CustomerID = 10 }; BALCustomer bal = new BALCustomer(new CustomerDataAccess()); bal.Add_A_New_Customer(customer); } } }

    Read the article

  • Capturing wildcards in java generics

    - by Rollerball
    From this orcale java tutorial: The WildcardError example produces a capture error when compiled: import java.util.List; public class WildcardError { void foo(List<?> i) { i.set(0, i.get(0)); } } After this error demonstration, they fix the problem by using a helper method: public class WildcardFixed { void foo(List<?> i) { fooHelper(i); } // Helper method created so that the wildcard can be captured // through type inference. private <T> void fooHelper(List<T> l) { l.set(0, l.get(0)); } } First, they say that the list input parameter (i) is seen as an Object: In this example, the compiler processes the i input parameter as being of type Object. Why then i.get(0) does not return an Object? if it was already passed in as such? Furthermore what is the point of using a <?> when then you have to use an helper method using <T>. Would not be better using directly which can be inferred?

    Read the article

  • Using Generics to return a literal string or from Dictionary<string, object>

    - by Mike
    I think I outsmarted myself this time. Feel free to edit the title also I could not think of a good one. I am reading from a file and then in that file will be a string because its like an xml file. But in the file will be a literal value or a "command" to get the value from the workContainer so <Email>[email protected]</Email> or <Email>[? MyEmail ?]</Email> What I wanted to do instead of writing ifs all over the place to put it in a generic function so logic is If Container command grab from container else grab string and convert to desired type Its up to the user to ensure the file is ok and the type is correct so another example is so <Answer>3</Answer> or <Answer>[? NumberOfSales ?]</Answer> This is the procedure I started to work on public class WorkContainer:Dictionary<string, object> { public T GetKeyValue<T>(string Parameter) { if (Parameter.StartsWith("[? ")) { string key = Parameter.Replace("[? ", "").Replace(" ?]", ""); if (this.ContainsKey(key)) { return (T)this[key]; } else { // may throw error for value types return default(T); } } else { // Does not Compile if (typeof(T) is string) { return Parameter } // OR return (T)Parameter } } } The Call would be mail.To = container.GetKeyValue<string>("[email protected]"); or mail.To = container.GetKeyValue<string>("[? MyEmail ?]"); int answer = container.GetKeyValue<int>("3"); or answer = container.GetKeyValue<int>("[? NumberOfSales ?]"); But it does not compile?

    Read the article

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