Search Results

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

Page 12/41 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Java template classes using generator or similar?

    - by Hugh Perkins
    Is there some library or generator that I can use to generate multiple templated java classes from a single template? Obviously Java does have a generics implementation itself, but since it uses type-erasure, there are lots of situations where it is less than adequate. For example, if I want to make a self-growing array like this: class EasyArray { T[] backingarray; } (where T is a primitive type), then this isn't possible. This is true for anything which needs an array, for example high-performance templated matrix and vector classes. It should probably be possible to write a code generator which takes a templated class and generates multiple instantiations, for different types, eg for 'double' and 'float' and 'int' and 'String'. Is there something that already exists that does this? Edit: note that using an array of Object is not what I'm looking for, since it's no longer an array of primitives. An array of primitives is very fast, and uses only as much space a sizeof(primitive) * length-of-array. An array of object is an array of pointers/references, that points to Double objects, or similar, which could be scattered all over the place in memory, require garbage collection, allocation, and imply a double-indirection for access. Edit2: good god, voted down for asking for something that probably doesn't currently exist, but is technically possible and feasible? Does that mean that people looking for ways to improve things have already left the java community? Edit3: Here is code to show the difference in performance between primitive and boxed arrays: int N = 10*1000*1000; double[]primArray = new double[N]; for( int i = 0; i < N; i++ ) { primArray[i] = 123.0; } Object[] objArray = new Double[N]; for( int i = 0; i < N; i++ ) { objArray[i] = 123.0; } tic(); primArray = new double[N]; for( int i = 0; i < N; i++ ) { primArray[i] = 123.0; } toc(); tic(); objArray = new Double[N]; for( int i = 0; i < N; i++ ) { objArray[i] = 123.0; } toc(); Results: double[] array: 148 ms Double[] array: 4614 ms Not even close!

    Read the article

  • C# Different class objects in one list

    - by jeah_wicer
    I have looked around some now to find a solution to this problem. I found several ways that could solve it but to be honest I didn't realize which of the ways that would be considered the "right" C# or OOP way of solving it. My goal is not only to solve the problems but also to develop a good set of code standards and I'm fairly sure there's a standard way to handle this problem. Let's say I have 2 types of printer hardwares with their respective classes and ways of communicating: PrinterType1, PrinterType2. I would also like to be able to later on add another type if neccessary. One step up in abstraction those have much in common. It should be possible to send a string to each one of them as an example. They both have variables in common and variables unique to each class. (One for instance communicates via COM-port and has such an object, while the other one communicates via TCP and has such an object). I would however like to just implement a List of all those printers and be able to go through the list and perform things as "Send(string message)" on all Printers regardless of type. I would also like to access variables like "PrinterList[0].Name" that are the same for both objects, however I would also at some places like to access data that is specific to the object itself (For instance in the settings window of the application where the COM-port name is set for one object and the IP/port number for another). So, in short something like: In common: Name Send() Specific to PrinterType1: Port Specific to PrinterType2: IP And I wish to, for instance, do Send() on all objects regardless of type and the number of objects present. I've read about polymorphism, Generics, interfaces and such, but I would like to know how this, in my eyes basic, problem typically would be dealt with in C# (and/or OOP in general). I actually did try to make a base class, but it didn't quite seem right to me. For instance I have no use of a "string Send(string Message)" function in the base class itself. So why would I define one there that needs to be overridden in the derived classes when I would never use the function in the base class ever in the first place? I'm really thankful for any answers. People around here seem very knowledgeable and this place has provided me with many solutions earlier. Now I finally have an account to answer and vote with too. EDIT: To additionally explain, I would also like to be able to access the objects of the actual printertype. For instance the Port variable in PrinterType1 which is a SerialPort object. I would like to access it like: PrinterList[0].Port.Open() and have access to the full range of functionality of the underlaying port. At the same time I would like to call generic functions that work in the same way for the different objects (but with different implementations): foreach (printer in Printers) printer.Send(message)

    Read the article

  • Entity Framework Generic Repository Error

    - by Jeff Ancel
    I am trying to create a very generic generics repository for my Entity Framework repository that has the basic CRUD statements and uses an Interface. I have hit a brick wall head first and been knocked over. Here is my code, written in a console application, using a Entity Framework Model, with a table named Hurl. Simply trying to pull back the object by its ID. Here is the full application code. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Objects; using System.Linq.Expressions; using System.Reflection; using System.Data.Objects.DataClasses; namespace GenericsPlay { class Program { static void Main(string[] args) { var hs = new HurlRepository(new hurladminEntity()); var hurl = hs.Load<Hurl>(h => h.Id == 1); Console.Write(hurl.ShortUrl); Console.ReadLine(); } } public interface IHurlRepository { T Load<T>(Expression<Func<T, bool>> expression); } public class HurlRepository : IHurlRepository, IDisposable { private ObjectContext _objectContext; public HurlRepository(ObjectContext objectContext) { _objectContext = objectContext; } public ObjectContext ObjectContext { get { return _objectContext; } } private Type GetBaseType(Type type) { Type baseType = type.BaseType; if (baseType != null && baseType != typeof(EntityObject)) { return GetBaseType(type.BaseType); } return type; } private bool HasBaseType(Type type, out Type baseType) { Type originalType = type.GetType(); baseType = GetBaseType(type); return baseType != originalType; } public IQueryable<T> GetQuery<T>() { Type baseType; if (HasBaseType(typeof(T), out baseType)) { return this.ObjectContext.CreateQuery<T>("[" + baseType.Name.ToString() + "]").OfType<T>(); } else { return this.ObjectContext.CreateQuery<T>("[" + typeof(T).Name.ToString() + "]"); } } public T Load<T>(Expression<Func<T, bool>> whereCondition) { return this.GetQuery<T>().Where(whereCondition).First(); } public void Dispose() { if (_objectContext != null) { _objectContext.Dispose(); } } } } Here is the error that I am getting: System.Data.EntitySqlException was unhandled Message="'Hurl' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly., near escaped identifier, line 3, column 1." Source="System.Data.Entity" Column=1 ErrorContext="escaped identifier" ErrorDescription="'Hurl' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly." This is where I am attempting to extract this information from. http://blog.keithpatton.com/2008/05/29/Polymorphic+Repository+For+ADONet+Entity+Framework.aspx

    Read the article

  • IEnumerable<CustomType> in PowerShell

    - by svick
    I'm trying to use Enumerable.ToList() in PowerShell. Apparently, to do that, I have to explicitly convert the object to IEnumerable<CustomType>, but I am unable to do that. It seems I can't correctly write IEnumerable<CustomType> in PowerShell. Both IEnumerable<string> and CustomType itself work correctly (the custom type I'm trying to use is called WpApiLib.Page), so I don't know what can I be doing wrong. PS C:\Users\Svick> [Collections.Generic.IEnumerable``1[System.String]] IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False IEnumerable`1 PS C:\Users\Svick> [WpApiLib.Page] IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Page System.Object PS C:\Users\Svick> [Collections.Generic.IEnumerable``1[WpApiLib.Page]] Unable to find type [Collections.Generic.IEnumerable`1[WpApiLib.Page]]: make su re that the assembly containing this type is loaded. At line:1 char:51 + [Collections.Generic.IEnumerable``1[WpApiLib.Page]] <<<<

    Read the article

  • C#: IEnumerable, GetEnumerator, a simple, simple example please!

    - by Andrew White
    Hi there, Trying to create an uebersimple class that implements get enumerator, but failing madly due to lack of simple / non-functioning examples out there. All I want to do is create a wrapper around a data structure (in this case a list, but I might need a dictionary later) and add some functions. public class Album { public readonly string Artist; public readonly string Title; public Album(string artist, string title) { Artist = artist; Title = title; } } public class AlbumList { private List<Album> Albums = new List<Album>; public Count { get { return Albums.Count; } } ..... //Somehow GetEnumerator here to return Album } Thanks!

    Read the article

  • Unity doesn't work

    - by Budda
    Yesterday I've implemented the code: CustomerProductManager productsManager = container.Resolve<CustomerProductManager>(); It was compilable and working. Today (probably I've modified something I am constantly getting the error: The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve(System.Type, string, params Microsoft.Practices.Unity.ResolverOverride[])' cannot be used with type arguments My collegue has the same source code and doesn't have same error. Why? How to resolve the problem? P.S. line "using Microsoft.Practices.Unity;" is present in usings section. I've tried to replace generic version with non-generic one: CustomerProductManager productsManager = (CustomerProductManager)container.Resolve(typeof(CustomerProductManager)); And got another error: No overload for method 'Resolve' takes '1' arguments It seems like one of the assemblies is not referenced.. but which one? I have 2 of them referenced: 1. Microsoft.Practices.Unity.dll 2. Microsoft.Practices.ServiceLocation.dll P.P.S. I've saw similar problem http://unity.codeplex.com/WorkItem/View.aspx?WorkItemId=8205 but it is resolved as "not a bug" Any thought will be helpful

    Read the article

  • C# Access the Properties of a Generic Object

    - by Jimbo
    I have a method that counts the number of Contacts each Supplier, Customer and Manufacturer has (this is a scenario to try make explaining easier!) The models are all created by Linq to SQL classes. Each Supplier, Customer and Manufacturer may have one or more Contacts public int CountContacts<TModel>(TModel entity) where TModel : class { return entity.Contacts.Count(); } The above of course doesnt work, because the 'entity' is generic and doesnt know whether it has the property 'Contacts'. Can someone help with how to achieve this?

    Read the article

  • Is it possible to specify a generic constraint for a type parameter to be convertible FROM another t

    - by fostandy
    Suppose I write a library with the following: public class Bar { /* ... */ } public class SomeWeirdClass<T> where T : ??? { public T BarMaker(Bar b) { // ... play with b T t = (T)b return (T) b; } } Later, I expect users to use my library by defining their own types which are convertible to Bar and using the SomeWeirdClass 'factory'. public class Foo { public static explicit operator Foo(Bar f) { return new Bar(); } } public class Demo { public static void demo() { Bar b = new Bar(); SomeWeirdClass<Foo> weird = new SomeWeirdClass<Foo>(); Foo f = weird.BarMaker(b); } } this will compile if i set where T : Foo but the problem is that I don't know about Foo at the library's compile time, and I actually want something more like where T : some class that can be instantiated, given a Bar Is this possible? From my limited knowledge it does not seem to be, but the ingenuity of the .NET framework and its users always surprises me... This may or not be related to the idea of static interface methods - at least, I can see the value in being able to specify the presence of factory methods to create objects (similar to the same way that you can already perform where T : new()) edit: Solution - thanks to Nick and bzIm - For other readers I'll provide a completed solution as I understand it: edit2: This solution requires Foo to expose a public default constructor. For an even stupider better solution that does not require this see the very bottom of this post. public class Bar {} public class SomeWeirdClass<T> where T : IConvertibleFromBar<T>, new() { public T BarMaker(Bar b) { T t = new T(); t.Convert(b); return t; } } public interface IConvertibleFromBar<T> { T Convert(Bar b); } public class Foo : IConvertibleFromBar<Foo> { public static explicit operator Foo(Bar f) { return null; } public Foo Convert(Bar b) { return (Foo) b; } } public class Demo { public static void demo() { Bar b = new Bar(); SomeWeirdClass<Foo> weird = new SomeWeirdClass<Foo>(); Foo f = weird.BarMaker(b); } } edit2: Solution 2: Create a type convertor factory to use: #region library defined code public class Bar {} public class SomeWeirdClass<T, TFactory> where TFactory : IConvertorFactory<Bar, T>, new() { private static TFactory convertor = new TFactory(); public T BarMaker(Bar b) { return convertor.Convert(b); } } public interface IConvertorFactory<TFrom, TTo> { TTo Convert(TFrom from); } #endregion #region user defined code public class BarToFooConvertor : IConvertorFactory<Bar, Foo> { public Foo Convert(Bar from) { return (Foo) from; } } public class Foo { public Foo(int a) {} public static explicit operator Foo(Bar f) { return null; } public Foo Convert(Bar b) { return (Foo) b; } } #endregion public class Demo { public static void demo() { Bar b = new Bar(); SomeWeirdClass<Foo, BarToFooConvertor> weird = new SomeWeirdClass<Foo, BarToFooConvertor>(); Foo f = weird.BarMaker(b); } }

    Read the article

  • Is it possible to specify a generic constraint for a type parameter to be convertible FROM another t

    - by fostandy
    Suppose I write a library with the following: public class Bar { /* ... */ } public class SomeWeirdClass<T> where T : ??? { public T BarMaker(Bar b) { // ... play with b T t = (T)b return (T) b; } } Later, I expect users to use my library by defining their own types which are convertible to Bar and using the SomeWeirdClass 'factory'. public class Foo { public static explicit operator Foo(Bar f) { return new Bar(); } } public class Demo { public static void demo() { Bar b = new Bar(); SomeWeirdClass<Foo> weird = new SomeWeirdClass<Foo>(); Foo f = weird.BarMaker(b); } } this will compile if i set where T : Foo but the problem is that I don't know about Foo at the library's compile time, and I actually want something more like where T : some class that can be instantiated, given a Bar Is this possible? From my limited knowledge it does not seem to be, but the ingenuity of the .NET framework and its users always surprises me... This may or not be related to the idea of static interface methods - at least, I can see the value in being able to specify the presence of factory methods to create objects (similar to the same way that you can already perform where T : new()) edit: Solution - thanks to Nick and bzIm - For other readers I'll provide a completed solution as I understand it: edit2: This solution requires Foo to expose a public default constructor. For an even stupider better solution that does not require this see the very bottom of this post. public class Bar {} public class SomeWeirdClass<T> where T : IConvertibleFromBar<T>, new() { public T BarMaker(Bar b) { T t = new T(); t.Convert(b); return t; } } public interface IConvertibleFromBar<T> { T Convert(Bar b); } public class Foo : IConvertibleFromBar<Foo> { public static explicit operator Foo(Bar f) { return null; } public Foo Convert(Bar b) { return (Foo) b; } } public class Demo { public static void demo() { Bar b = new Bar(); SomeWeirdClass<Foo> weird = new SomeWeirdClass<Foo>(); Foo f = weird.BarMaker(b); } } edit2: Solution 2: Create a type convertor factory to use: #region library defined code public class Bar {} public class SomeWeirdClass<T, TFactory> where TFactory : IConvertorFactory<Bar, T>, new() { private static TFactory convertor = new TFactory(); public T BarMaker(Bar b) { return convertor.Convert(b); } } public interface IConvertorFactory<TFrom, TTo> { TTo Convert(TFrom from); } #endregion #region user defined code public class BarToFooConvertor : IConvertorFactory<Bar, Foo> { public Foo Convert(Bar from) { return (Foo) from; } } public class Foo { public Foo(int a) {} public static explicit operator Foo(Bar f) { return null; } public Foo Convert(Bar b) { return (Foo) b; } } #endregion public class Demo { public static void demo() { Bar b = new Bar(); SomeWeirdClass<Foo, BarToFooConvertor> weird = new SomeWeirdClass<Foo, BarToFooConvertor>(); Foo f = weird.BarMaker(b); } }

    Read the article

  • Generic method to create deep copy of all elements in a collection

    - by bwarner
    I have various ObservableCollections of different object types. I'd like to write a single method that will take a collection of any of these object types and return a new collection where each element is a deep copy of elements in the given collection. Here is an example for a specifc class private static ObservableCollection<PropertyValueRow> DeepCopy(ObservableCollection<PropertyValueRow> list) { ObservableCollection<PropertyValueRow> newList = new ObservableCollection<PropertyValueRow>(); foreach (PropertyValueRow rec in list) { newList.Add((PropertyValueRow)rec.Clone()); } return newList; } How can I make this method generic for any class which implements ICloneable?

    Read the article

  • Circular reference error when outputting LINQ to SQL entities with relationships as JSON in an ASP.N

    - by roosteronacid
    Here's a design-view screenshot of my dbml-file. The relationships are auto-generated by foreign keys on the tables. When I try to serialize a query-result into JSON I get a circular reference error..: public ActionResult Index() { return Json(new DataContext().Ingredients.Select(i => i)); } But if I create my own collection of "bare" Ingredient objects, everything works fine..: public ActionResult Index() { return Json(new Entities.Ingredient[] { new Entities.Ingredient(), new Entities.Ingredient(), new Entities.Ingredient() }); } ... Also; serialization works fine if I remove the relationships on my tables. How can I serialize objects with relationships, without having to turn to a 3rd-party library? I am perfectly fine with just serializing the "top-level" objects of a given collection.. That is; without the relationships being serialized as well.

    Read the article

  • Generic foreach loop in C#.

    - by mcoolbeth
    The compiler, given the following code, tells me "Use of unassigned local variable 'x'." Any thoughts? public delegate Y Function<X,Y>(X x); public class Map<X,Y> { private Function<X,Y> F; public Map(Function f) { F = f; } public Collection<Y> Over(Collection<X> xs){ List<Y> ys = new List<Y>(); foreach (X x in xs) { X x2 = x;//ys.Add(F(x)); } return ys; } }

    Read the article

  • Help me understand these generic method warnings

    - by Raj
    Folks, I have a base class, say: public class BaseType { private String id; ... } and then three subclasses: public class TypeA extends BaseType { ... } public class TypeB extends BaseType { ... } public class TypeC extends BaseType { ... } I have a container class that maintains lists of objects of these types: public class Container { private List<TypeA> aList; private List<TypeB> bList; private List<TypeC> cList; // finder method goes here } And now I want to add a finder method to container that will find an object from one of the lists. The finder method is written as follows: public <T extends BaseType> T find( String id, Class<T> clazz ) { final List<T> collection; if( clazz == TypeA.class ) { collection = (List<T>)aList; } else if( clazz == TypeB.class ) { collection = (List<T>)bList; } else if( clazz == TypeC.class ) { collection = (List<T>)cList; } else return null; for( final BaseType value : collection ) { if( value.getId().equals( id ) ) { return (T)value; } } return null; } My question is this: If I don't add all the casts to T in my finder above, I get compile errors. I think the compile should be able to infer the types based on parametrization of the generic method (). Can anyone explain this? Thanks. -Raj

    Read the article

  • Invoking EventHandler generic, TargetParameterCountException

    - by Am
    Hi, I have a DirectoryMonitor class which works on another thread. It has the following events declared: public class DirectoryMonitor { public event EventHandler<MonitorEventArgs> CreatedNewBook; public event EventHandler ScanStarted; .... } public class MonitorEventArgs : EventArgs { public Book Book { get; set; } } There is a form using that monitor, and upon receiving the events, it should update the display. Now, this works: void DirectoryMonitor_ScanStarted(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(this.DirectoryMonitor_ScanStarted)); } else {...} } But this throws TargetParameterCountException: void DirectoryMonitor_CreatedNewBook(object sender, MonitorEventArgs e) { if (InvokeRequired) { Invoke(new EventHandler<MonitorEventArgs>(this.DirectoryMonitor_CreatedNewBook)); } else {...} } What am I missing?

    Read the article

  • Delphi: Using Enumerators to filter TList<T: class> by class type?

    - by afrazier
    Okay, this might be confusing. What I'm trying to do is use an enumerator to only return certain items in a generic list based on class type. Given the following hierarchy: type TShapeClass = class of TShape; TShape = class(TObject) private FId: Integer; public function ToString: string; override; property Id: Integer read FId write FId; end; TCircle = class(TShape) private FDiameter: Integer; public property Diameter: Integer read FDiameter write FDiameter; end; TSquare = class(TShape) private FSideLength: Integer; public property SideLength: Integer read FSideLength write FSideLength; end; TShapeList = class(TObjectList<TShape>) end; How can I extend TShapeList such that I can do something similar to the following: procedure Foo; var ShapeList: TShapeList; Shape: TShape; Circle: TCircle; Square: TSquare; begin // Create ShapeList and fill with TCircles and TSquares for Circle in ShapeList<TCircle> do begin // do something with each TCircle in ShapeList end; for Square in ShapeList<TSquare> do begin // do something with each TSquare in ShapeList end; for Shape in ShapeList<TShape> do begin // do something with every object in TShapeList end; end; I've tried extending TShapeList using an adapted version of Primoz Gabrijelcic's bit on Parameterized Enumerators using a factory record as follows: type TShapeList = class(TObjectList<TShape>) public type TShapeFilterEnumerator<T: TShape> = record private FShapeList: TShapeList; FClass: TShapeClass; FIndex: Integer; function GetCurrent: T; public constructor Create(ShapeList: TShapeList); function MoveNext: Boolean; property Current: T read GetCurrent; end; TShapeFilterFactory<T: TShape> = record private FShapeList: TShapeList; public constructor Create(ShapeList: TShapeList); function GetEnumerator: TShapeFilterEnumerator<T>; end; function FilteredEnumerator<T: TShape>: TShapeFilterFactory<T>; end; Then I modified Foo to be: procedure Foo; var ShapeList: TShapeList; Shape: TShape; Circle: TCircle; Square: TSquare; begin // Create ShapeList and fill with TCircles and TSquares for Circle in ShapeList.FilteredEnumerator<TCircle> do begin // do something with each TCircle in ShapeList end; for Square in ShapeList.FilteredEnumerator<TSquare> do begin // do something with each TSquare in ShapeList end; for Shape in ShapeList.FilteredEnumerator<TShape> do begin // do something with every object in TShapeList end; end; However, Delphi 2010 is throwing an error when I try to compile Foo about Incompatible types: TCircle and TShape. If I comment out the TCircle loop, then I get a similar error about TSquare. If I comment the TSquare loop out as well, the code compiles and works. Well, it works in the sense that it enumerates every object since they all descend from TShape. The strange thing is that the line number that the compiler indicates is 2 lines beyond the end of my file. In my demo project, it indicated line 177, but there's only 175 lines. Is there any way to make this work? I'd like to be able to assign to Circle directly without going through any typecasts or checking in my for loop itself.

    Read the article

  • Configuring Unity with a closed generic constructor parmater

    - by fearofawhackplanet
    I've been trying to read the article here but I still can't understand it. I have a constructor resembling the following: IOrderStore orders = new OrderStore(new Repository<Order>(new OrdersDataContext())); The constructor for OrderStore: public OrderStore(IRepository<Order> orderRepository) Constructor for Repository<T>: public Repository(DataContext dataContext) How do I set this up in the Unity config file? UPDATE: I've spent the last few hours banging my head against this, and although I'm not really any closer to getting it right I think at least I can be a little more specific about the problem. I've got my IRespository<T> working ok: <typeAlias alias="IRepository" type="MyAssembly.IRepository`1, MyAssembly" /> <typeAlias alias="Repository" type="MyAssembly.Repository`1, MyAssembly" /> <typeAlias alias="OrdersDataContext" type="MyAssembly.OrdersDataContext, MyAssembly" /> <types> <type type="OrdersDataContext"> <typeConfig> <constructor /> <!-- ensures paramaterless constructor used --> </typeConfig> </type> <type type="IRepository" mapTo="Repository"> <typeConfig> <constructor> <param name="dataContext" parameterType="OrdersDataContext"> <dependency /> </param> </constructor> </typeConfig> </type> </types> So now I can get an IRepository like so: IRepository rep = _container.Resolve(); and that all works fine. The problem now is when trying to add the configuration for IOrderStore <type type="IOrderStore" mapTo="OrderStore"> <typeConfig> <constructor> <param name="ordersRepository" parameterType="IRepository"> <dependency /> </param> </constructor> </typeConfig> </type> When I add this, Unity blows up when trying to load the config file. The error message is OrderStore does not have a constructor that takes the parameters (IRepository`1). What I think this is complaining about is because the OrderStore constructor takes a closed IRepository generic type, ie OrderStore(IRepository<Order>) and not OrderStore(IRepository<T>) I don't have any idea how to resolve this.

    Read the article

  • Java Builder pattern with Generic type bounds

    - by I82Much
    Hi all, I'm attempting to create a class with many parameters, using a Builder pattern rather than telescoping constructors. I'm doing this in the way described by Joshua Bloch's Effective Java, having private constructor on the enclosing class, and a public static Builder class. The Builder class ensures the object is in a consistent state before calling build(), at which point it delegates the construction of the enclosing object to the private constructor. Thus public class Foo { // Many variables private Foo(Builder b) { // Use all of b's variables to initialize self } public static final class Builder { public Builder(/* required variables */) { } public Builder var1(Var var) { // set it return this; } public Foo build() { return new Foo(this); } } } I then want to add type bounds to some of the variables, and thus need to parametrize the class definition. I want the bounds of the Foo class to be the same as that of the Builder class. public class Foo<Q extends Quantity> { private final Unit<Q> units; // Many variables private Foo(Builder<Q> b) { // Use all of b's variables to initialize self } public static final class Builder<Q extends Quantity> { private Unit<Q> units; public Builder(/* required variables */) { } public Builder units(Unit<Q> units) { this.units = units; return this; } public Foo build() { return new Foo<Q>(this); } } } This compiles fine, but the compiler is allowing me to do things I feel should be compiler errors. E.g. public static final Foo.Builder<Acceleration> x_Body_AccelField = new Foo.Builder<Acceleration>() .units(SI.METER) .build(); Here the units argument is not Unit<Acceleration> but Unit<Length>, but it is still accepted by the compiler. What am I doing wrong here? I want to ensure at compile time that the unit types match up correctly.

    Read the article

  • How can I use Convert.ChangeType to convert string into numerics with group separator?

    - by Loic
    Hello, I want to make a generic string to numeric converter, and provide it as a string extension, so I wrote the following code: public static bool TryParse<T>( this string text, out T result, IFormatProvider formatProvider ) where T : struct try { result = (T)Convert.ChangeType( text, typeof( T ), formatProvider ); return true; } catch(... I call it like this: int value; var ok = "123".TryParse(out value, NumberFormatInfo.CurrentInfo) It works fine until I want to use a group separator: As I live in France, where the thousand separator is a space and the decimal separator is a comma, the string "1 234 567,89" should be equals to 1234567.89 (in Invariant culture). But, the function crashes! When a try to perform a non generic conversion, like double.Parse(...), I can use an overload which accepts a NumberStyles parameter. I specify NumberStyles.Number and this time it works! So, the questions are : Why the parsing does not respect my NumberFormatInfo (where the NumberGroupSeparator is well specified to a space, as I specified in my OS) How could I make work the generic version with Convert.ChangeTime, as it has no overload wich accepts a NumberStyles parameter ?

    Read the article

  • Avoiding unsafe cast for generic situation involving runtime passing of class

    - by Bart van Heukelom
    public class AutoKeyMap<K,V> { public interface KeyGenerator<K> { public K generate(); } private KeyGenerator<K> generator; public AutoKeyMap(Class<K> keyType) { // WARNING: Unchecked cast from AutoKeyMap.IntKeyGen to AutoKeyMap.KeyGenerator<K> if (keyType == Integer.class) generator = (KeyGenerator<K>) new IntKeyGen(); else throw new RuntimeException("Cannot generate keys for " + keyType); } public void put(V value) { K key = generator.generate(); ... } private static class IntKeyGen implements KeyGenerator<Integer> { private final AtomicInteger ai = new AtomicInteger(1); @Override public Integer generate() { return ai.getAndIncrement(); } } } In the code sample above, what is the correct way to prevent the given warning, without adding a @SuppressWarnings, if any?

    Read the article

  • Create a Generic IEnumerable<T> given a IEnumerable and the member datatypes

    - by ilias
    Hi, I get an IEnumerable which I know is a object array. I also know the datatype of the elements. Now I need to cast this to an IEnumerable<T, where T is a supplied type. For instance IEnumerable results = GetUsers(); IEnumerable<T> users = ConvertToTypedIEnumerable(results, typeof(User)); I now want to cast/ convert this to IEnumerable<User. Also, I want to be able to do this for any type. I cannot use IEnumerable.Cast<, because for that I have to know the type to cast it to at compile time, which I don't have. I get the type and the IEnumerable at runtime. - Thanks

    Read the article

  • Performance penalty of typecasting and boxing/unboxing types in C# when storing generic values

    - by kitsune
    I have a set-up similar to WPF's DependencyProperty and DependencyObject system. My properties however are generic. A BucketProperty has a static GlobalIndex (defined in BucketPropertyBase) which tracks all BucketProperties. A Bucket can have many BucketProperties of any type. A Bucket saves and gets the actual values of these BucketProperties... now my question is, how to deal with the storage of these values, and what is the penalty of using a typecasting when retrieving them? I currently use an array of BucketEntries that save the property values as simple objects. Is there any better way of saving and returning these values? Beneath is a simpliefied version: public class BucketProperty<T> : BucketPropertyBase { } public class Bucket { private BucketEntry[] _bucketEntries; public void SaveValue<T>(BucketProperty<T> property, T value) { SaveBucketEntry(property.GlobalIndex, value) } public T GetValue<T>(BucketProperty<T> property) { return (T)FindBucketEntry(property.GlobalIndex).Value; } } public class BucketEntry { private object _value; private uint _index; public BucketEntry(uint globalIndex, object value) { ... } }

    Read the article

  • Calling a method with an arg of Class<T> where T is a parameterized type

    - by Brian Ferris
    I'm attempting to call a constructor method that looks like: public static SomeWrapper<T> method(Class<T> arg); When T is an unparameterized type like String or Integer, calling is straightforward: SomeWrapper<String> wrapper = method(String.class); Things get tricky when T is a parameterized type like List<String>. The following is not valid: SomeWrapper<List<String>> wrapper = method(List<String>.class); About the only thing I could come up with is: List<String> o = new ArrayList<String>(); Class<List<String>> c = (Class<List<String>>) o.getClass(); SomeWrapper<List<String>> wrapper = method(c); Surely there is an easier way that doesn't require the construction of an additional object?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >