Search Results

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

Page 28/41 | < Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >

  • PropertyInfo.GetValue() - how do you index into a generic parameter using reflection in C#?

    - by flesh
    This (shortened) code.. for (int i = 0; i < count; i++) { object obj = propertyInfo.GetValue(Tcurrent, new object[] { i }); } .. is throwing a 'TargetParameterCountException : Parameter count mismatch' exception. The underlying type of 'propertyInfo' is a Collection of some T. 'count' is the number of items in the collection. I need to iterate through the collection and perform an operation on obj. Advice appreciated.

    Read the article

  • Trouble with abstract generic methods

    - by DanM
    Let's say I have a class library that defines a couple entity interfaces: public interface ISomeEntity { /* ... */ } public interface ISomeOtherEntity { /* ... */ } This library also defines an IRepository interface: public interface IRepository<TEntity> { /* ... */ } And finally, the library has an abstract class called RepositorySourceBase (see below), which the main project needs to implement. The goal of this class is to allow the base class to grab new Repository objects at runtime. Because certain repositories are needed (in this example a repository for ISomeEntity and ISomeOtherEntity), I'm trying to write generic overloads of the GetNew<TEntity>() method. The following implementation doesn't compile (the second GetNew() method gets flagged as "already defined" even though the where clause is different), but it gets at what I'm trying to accomplish: public abstract class RepositorySourceBase // This doesn't work! { public abstract Repository<TEntity> GetNew<TEntity>() where TEntity : SomeEntity; public abstract Repository<TEntity> GetNew<TEntity>() where TEntity : SomeOtherEntity; } The intended usage of this class would be something like this: public class RepositorySourceTester { public RepositorySourceTester(RepositorySourceBase repositorySource) { var someRepository = repositorySource.GetNew<ISomeEntity>(); var someOtherRepository = repositorySource.GetNew<ISomeOtherEntity>(); } } Meanwhile, over in my main project (which references the library project), I have implementations of ISomeEntity and ISomeOtherEntity: public class SomeEntity : ISomeEntity { /* ... */ } public class SomeOtherEntity : ISomeOtherEntity { /* ... */ } The main project also has an implementation for IRepository<TEntity>: public class Repository<TEntity> : IRepository<TEntity> { public Repository(string message) { } } And most importantly, it has an implementation of the abstract RepositorySourceBase: public class RepositorySource : RepositorySourceBase { public override Repository<SomeEntity> GetNew() { return new Repository<SomeEntity>("stuff only I know"); } public override Repository<SomeOtherEntity> GetNew() { return new Repository<SomeOtherEntity>("other stuff only I know"); } } Just as with RepositorySourceBase, the second GetNew() method gets flagged as "already defined". So, C# basically think I'm repeating the same method because there's no way to distinguish the methods from parameters, but if you look at my usage example, it seems like I should be able to distinguish which GetNew() I want from the generic type parameter, e.g, <ISomeEntity> or <ISomeOtherEntity>. What do I need to do to get this to work?

    Read the article

  • Is there a nice way of having static generic parameters is Java?

    - by Chris
    Hello, recently I'm writing some functions that I take from Haskell and translate into Java. One of the main problems I have is I cannot easily create a static property with a generic type. Let me explain by a little example... // An interface to implement functions public interface Func<P, R> { public R apply(P p); } // What I want to do... (incorrect in Java) public class ... { public static <T> Func<T, T> identity = new Func<T, T>() { public T apply(T p) { return p; } } } // What I do right now public class ... { private static Func<Object, Object> identity = new Func<Object, Object>() { public Object apply(Object p) { return p; } } @SuppressWarnings("unchecked") public static <T> Func<T, T> getIdentity() { return (Func<T, T>)identity; } } Are there any easier ways to do something like that? What kind of problems might arise if the syntax I used would be valid?

    Read the article

  • Operator as and generic classes

    - by abatishchev
    I'm writing .NET On-the-Fly compiler for CLR scripting and want execution method make generic acceptable: object Execute() { return type.InvokeMember(..); } T Execute<T>() { return Execute() as T; /* doesn't work: The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint */ // also neither typeof(T) not T.GetType(), so on are possible return (T) Execute(); // ok } But I think operator as will be very useful: if result type isn't T method will return null, instead of an exception! Is it possible to do?

    Read the article

  • How could I know if an object is derived from a specific generic class?

    - by Edison Chuang
    Suppose that I have an object then how could I know if the object is derived from a specific generic class. For example: public class GenericClass<T> { } public bool IsDeriveFrom(object o) { return o.GetType().IsSubclassOf(typeof(GenericClass)); //will throw exception here } please notice that the code above will throw an exception. The type of the generic class cannot be retrieved directly because there is no type for a generic class without a type parameter provided.

    Read the article

  • Generic overloading tells me this is the same function. Not agree.

    - by serhio
    base class: Class List(Of T) Function Contains(ByVal value As T) As Boolean derived class: Class Bar : List(Of Exception) ' Exception type as example ' Function Contains(Of U)(ByVal value As U) As Boolean compiler tells me that that two are the same, so I need to declare Overloads/new this second function. But I want use U to differentiate the type (one logic) like NullReferenceException, ArgumentNull Exception, etc. but want to leave the base function(no differentiation by type - other logic) as well.

    Read the article

  • Get derived class type from a base's class static method

    - by Marco Bettiolo
    Hi, i would like to get the type of the derived class from a static method of its base class. How can this be accomplished? Thanks! class BaseClass { static void Ping () { Type t = this.GetType(); // should be DerivedClass, but it is not possible with a static method } } class DerivedClass : BaseClass {} // somewhere in the code DerivedClass.Ping();

    Read the article

  • Generic Dictionary - Getting Convertion Error

    - by pm_2
    The following code is giving me an error: // GetDirectoryList() returns Dictionary<string, DirectoryInfo> Dictionary<string, DirectoryInfo> myDirectoryList = GetDirectoryList(); // The following line gives a compile error foreach (Dictionary<string, DirectoryInfo> eachItem in myDirectoryList) The error it gives is as follows: Cannot convert type 'System.Collections.Generic.KeyValuePair<string,System.IO.DirectoryInfo>' to 'System.Collections.Generic.Dictionary<string,System.IO.DirectoryInfo>’ My question is: why is it trying to perform this conversion? Can I not use a foreach loop on this type of object?

    Read the article

  • Generic Func<> as parameter to base method

    - by WestDiscGolf
    I might be losing the plot, but I hope someone can point me in the right direction. What am I trying to do? I'm trying to write some base methods which take Func< and Action so that these methods handle all of the exception handling etc. so its not repeated all over the place but allow the derived classes to specify what actions it wants to execute. So far this is the base class. public abstract class ServiceBase<T> { protected T Settings { get; set; } protected ServiceBase(T setting) { Settings = setting; } public void ExecAction(Action action) { try { action(); } catch (Exception exception) { throw new Exception(exception.Message); } } public TResult ExecFunc<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> function) { try { /* what goes here?! */ } catch (Exception exception) { throw new Exception(exception.Message); } } } I want to execute an Action in the following way in the derived class (this seems to work): public void Delete(string application, string key) { ExecAction(() => Settings.Delete(application, key)); } And I want to execute a Func in a similar way in the derived class but for the life of me I can't seem to workout what to put in the base class. I want to be able to call it in the following way (if possible): public object Get(string application, string key, int? expiration) { return ExecFunc(() => Settings.Get(application, key, expiration)); } Am I thinking too crazy or is this possible? Thanks in advance for all the help.

    Read the article

  • Reflection for Class of generic parameter in Java?

    - by hatboysam
    Imagine the following scenario: class MyClass extends OtherClass<String>{ String myName; //Whatever } class OtherClass<T> { T myfield; } And I am analyzing MyClass using reflection specifically (MyClass.class).getDeclaredFields(), in this case I will get the following fields (and Types, using getType() of the Field): myName --> String myField --> T I want to get the actual Type for T, which is known at runtime due to the explicit "String" in the extends notation, how do I go about getting the non-genetic type of myField?

    Read the article

  • Java - How to pass a Generic parameter as Class<T> to a constructor

    - by Joe Almore
    I have a problem here that still cannot solve, the thing is I have this abstract class: public abstract class AbstractBean<T> { private Class<T> entityClass; public AbstractBean(Class<T> entityClass) { this.entityClass = entityClass; }... Now I have another class that inherits this abstract: @Stateless @LocalBean public class BasicUserBean<T extends BasicUser> extends AbstractBean<T> { private Class<T> user; public BasicUserBean() { super(user); // Error: cannot reference user before supertype contructor has been called. } My question is how can I make this to work?, I am trying to make the class BasicUserBean inheritable, so if I have class PersonBean which inherits BasicUserBean then I could set in the Generic the entity Person which also inherits the entity BasicUser. And it will end up being: @Stateless @LocalBean public class PersonBean extends BasicUserBean<Person> { public PersonBean() { super(Person.class); } ... I just want to inherit the basic functionality from BasicUserBean to all descendants, so I do not have to repeat the same code among all descendants. Thanks!.

    Read the article

  • Operator overloading in generic struct: can I create overloads for specific kinds(?) of generic?

    - by Carson Myers
    I'm defining physical units in C#, using generic structs, and it was going okay until I got the error: One of the parameters of a binary operator must be the containing type when trying to overload the mathematical operators so that they convert between different units. So, I have something like this: public interface ScalarUnit { } public class Duration : ScalarUnit { } public struct Scalar<T> where T : ScalarUnit { public readonly double Value; public Scalar(double Value) { this.Value = Value; } public static implicit operator double(Scalar<T> Value) { return Value.Value; } } public interface VectorUnit { } public class Displacement : VectorUnit { } public class Velocity : VectorUnit { } public struct Vector<T> where T : VectorUnit { #... public static Vector<Velocity> operator /(Vector<Displacement> v1, Scalar<Duration> v2) { return new Vector<Velocity>(v1.Magnitude / v2, v1.Direction); } } There aren't any errors for the + and - operators, where I'm just working on a Vector<T>, but when I substitute a unit for T, suddenly it doesn't like it. Is there a way to make this work? I figured it would work, since Displacement implements the VectorUnit interface, and I have where T : VectorUnit in the struct header. Am I at least on the right track here? I'm new to C# so I have difficulty understanding what's going on sometimes.

    Read the article

  • How to create a generic C# method that can return either double or decimal?

    - by CrimsonX
    I have a method like this: private static double ComputePercentage(ushort level, ushort capacity) { double percentage; if(capacity == 1) percentage = 1; // do calculations... return percentage; } Is it possible to make it of a generic type like "type T" where it can return either decimal or double, depending on the type of method expected (or the type put into the function?) I tried something like this and I couldn't get it to work, because I cannot assign a number like "1" to a generic type. I also tried using the "where T :" after ushort capacity) but I still couldn't figure it out. private static T ComputePercentage<T>(ushort level, ushort capacity) { T percentage; if(capacity == 1) percentage = 1; // error here // do calculations... return percentage; } Is this even possible? I wasn't sure, but I thought this post might suggest that what I'm trying to do is just plain impossible.

    Read the article

  • C# Using Reflection to Get a Generic Object's (and its Nested Objects) Properties

    - by Jimbo
    This is a scenario created to help understand what Im trying to achieve. I am trying to create a method that returns the specified property of a generic object e.g. public object getValue<TModel>(TModel item, string propertyName) where TModel : class{ PropertyInfo p = typeof(TModel).GetProperty(propertyName); return p.GetValue(item, null); } The code above works fine if you're looking for a property on the TModel item e.g. string customerName = getValue<Customer>(customer, "name"); However, if you want to find out what the customer's group's name is, it becomes a problem: e.g. string customerGroupName = getValue<Customer>(customer, "Group.name"); Hoping someone can give me some insight on this way out scenario - thanks.

    Read the article

  • Delphi 2010 - Why can't I declare an abstract method with a generic type parameter?

    - by James
    I am trying to do the following in Delphi 2010: TDataConverter = class abstract public function Convert<T>(const AData: T): string; virtual; abstract; end; However, I keep getting the following compiler error: E2533 Virtual, dynamic and message methods cannot have type parameters I don't quite understand the reason why I can't do this. I can do this in C# e.g. public abstract class DataConverter { public abstract string Convert<T>(T data); } Anyone know the reasoning behind this?

    Read the article

  • returning a Void object

    - by Robert
    What is the correct way to return a Void type, when it isn't a primitive? Eg. I currently use null as below. interface B<E>{ E method(); } class A implements B<Void>{ public Void method(){ // do something return null; } }

    Read the article

  • Any way to make a generic List where I can add a type AND a subtype?

    - by user383178
    I understand why I cannot do the following: private class Parent { }; private class Child extends Parent { }; private class GrandChild extends Child { }; public void wontCompile(List<? extends Parent> genericList, Child itemToAdd) { genericList.add(itemToAdd); } My question is there ANY practical way to have a typesafe List where you can call add(E) where E is known to be only a Parent or a Child? I vaguely remember some use of the "|" operator as used for wildcard bounds, but I cannot find it in the spec... Thanks!

    Read the article

  • Is this a good way to generically deserialize objects?

    - by Damien Wildfire
    I have a stream onto which serialized objects representing messages are dumped periodically. The objects are one of a very limited number of types, and other than the actual sequence of bytes that arrives, I have no way of knowing what type of message it is. I would like to simply try to deserialize it as an object of a particular type, and if an exception is thrown, try again with the next type. I have an interface that looks like this: public interface IMessageHandler<T> where T : class, IMessage { T Handle(string message); } // elsewhere: // (These are all xsd.exe-generated classes from an XML schema.) public class AppleMessage : IMessage { ... } public class BananaMessage : IMessage { ... } public class CoconutMessage : IMessage { ... } Then I wrote a GenericHandler<T> that looks like this: public class GenericHandler<T> : IMessageHandler<T> where T: class, IMessage { public class MessageHandler : IMessageHandler { T IMessageHandler.Handle(string message) { T result = default(T); try { // This utility method tries to deserialize the object with an // XmlSerializer as if it were an object of type T. result = Utils.SerializationHelper.Deserialize<T>(message); } catch (InvalidCastException e) { result = default(T); } return result; } } } Two questions: Using my GenericHandler<T> (or something similar to it), I'd now like to populate a collection with handlers that each handle a different type. Then I want to invoke each handler's Handle method on a particular message to see if it can be deserialized. If I get a null result, move onto the next handler; otherwise, the message has been deserialized. Can this be done? Is there a better way to deserialize data of unknown (but restricted) type?

    Read the article

  • Force calling the derived class implementation within a generic function in C#?

    - by Adam Hardy
    Ok so I'm currently working with a set of classes that I don't have control over in some pretty generic functions using these objects. Instead of writing literally tens of functions that essentially do the same thing for each class I decided to use a generic function instead. Now the classes I'm dealing with are a little weird in that the derived classes share many of the same properties but the base class that they are derived from doesn't. One such property example is .Parent which exists on a huge number of derived classes but not on the base class and it is this property that I need to use. For ease of understanding I've created a small example as follows: class StandardBaseClass {} // These are simulating the SMO objects class StandardDerivedClass : StandardBaseClass { public object Parent { get; set; } } static class Extensions { public static object GetParent(this StandardDerivedClass sdc) { return sdc.Parent; } public static object GetParent(this StandardBaseClass sbc) { throw new NotImplementedException("StandardBaseClass does not contain a property Parent"); } // This is the Generic function I'm trying to write and need the Parent property. public static void DoSomething<T>(T foo) where T : StandardBaseClass { object Parent = ((T)foo).GetParent(); } } In the above example calling DoSomething() will throw the NotImplemented Exception in the base class's implementation of GetParent(), even though I'm forcing the cast to T which is a StandardDerivedClass. This is contrary to other casting behaviour where by downcasting will force the use of the base class's implementation. I see this behaviour as a bug. Has anyone else out there encountered this?

    Read the article

  • How to check if TypeIdenitifier(T) is an Object?

    - by John
    I'm creating a generic list class that has a member of type Array(Array of ). The problem is the class descruction,because the class is supposed to be used for types from byte to types inheriting TObject. Specifically: destructor Destroy; var elem:T; begin /*if(T is Tobject) then //Check if T inherits TObject {Compiler error!} for elem in FData do TObject(elem).Free;*/ // do not know how to do it SetLength(FItems,0); //FItems : Array of T inherited Destroy; end; How do I check if T is TObject so I can free every member if the typeidenitifier is a class,for example?

    Read the article

  • Invoking static methods containing Generic Parameters using Reflection.

    - by AJP
    While executing the following code i gets this error "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true." class Program { static void Main(string[] args) { MethodInfo MI = typeof(MyClass).GetMethod("TestProc"); MI.MakeGenericMethod(new [] {typeof(string)}); MI.Invoke(null, new [] {"Hello"}); } } class MyClass { public static void TestProc<T>(T prefix) { Console.WriteLine("Hello"); } } Please help.

    Read the article

  • If I use a facade class with generic methods to access the JPA API, how should I provide additional processing for specific types?

    - by Shaun
    Let's say I'm making a fairly simple web application using JAVA EE specs (I've heard this is possible). In this app, I only have about 10 domain/data objects, and these are represented by JPA Entities. Architecturally, I would consider the JPA API to perform the role of a DAO. Of course, I don't want to use the EntityManager directly in my UI (JSF) and I need to manage transactions, so I delegate these tasks to the so-called service layer. More specifically, I would like to be able to handle these tasks in a single DataService class (often also called CrudService) with generic methods. See this article by Adam Bien for an example interface: http://www.adam-bien.com/roller/abien/entry/generic_crud_service_aka_dao My project differs from that article in that I can't use EJBs, so my service classes are essentially just named beans and I handle transactions manually. Regardless, what I want is a single interface for simple CRUD operations on my data objects because having a different class for each data type would lead to a lot of duplicate and/or unnecessary code. Ideally, my views would be able to use a method such as public <T> List<T> findAll(Class<T> type) { ... } to retrieve data. Using JSF, it might look something like this: <h:dataTable value="#{dataService.findAll(data.class)}" var="d"> ... </h:dataTable> Similarly, after validating forms, my controller could submit the data with a method such as: public <T> void add(T entity) { ... } Granted, you'd probably actually want to return something useful to the caller. In any case, this works well if your data can be treated as homogenous in this manner. Alas, it breaks down when you need to perform additional processing on certain objects before passing them on to JPA. For example, let's say I'm dealing with Books and Authors which have a many-to-many relationship. Each Book has a set of IDs referring to its authors, and each Author has a set of IDs referring to their books. Normally, JPA can manage this kind of relationship for you, but in some cases it can't (for example, the google app engine JPA provider doesn't support this). Thus, when I persist a new book for example, I may need to update the corresponding author entities. My question, then, is if there's an elegant way to handle this or if I should reconsider the sanity of my whole design. Here's a couple ways I see of dealing with it: The instanceof operator. I could use this to target certain classes when special processing is needed. Perhaps maintainability suffers and it isn't beautiful code, but if there's only 10 or so domain objects it can't be all that bad... could it? Make a different service for each entity type (ie, BookService and AuthorService). All services would inherit from a generic DataService base class and override methods if special processing is needed. At this point, you could probably also just call them DAOs instead. As always, I appreciate the help. Let me know if any clarifications are needed, as I left out many smaller details.

    Read the article

  • How to filter List<T> with LINQ and Reflection

    - by Ehsan Sajjad
    i am getting properties via reflection and i was doing like this to iterate on the list. private void HandleListProperty(object oldObject, object newObject, string difference, PropertyInfo prop) { var oldList = prop.GetValue(oldObject, null) as IList; var newList = prop.GetValue(newObject, null) as IList; if (prop.PropertyType == typeof(List<DataModel.ScheduleDetail>)) { List<DataModel.ScheduleDetail> ScheduleDetailsOld = oldList as List<DataModel.ScheduleDetail>; List<DataModel.ScheduleDetail> ScheduleDetailsNew = newList as List<DataModel.ScheduleDetail>; var groupOldSchedules = ScheduleDetailsOld .GroupBy(x => x.HomeHelpID) .SelectMany(s => s.DistinctBy(d => d.HomeHelpID) .Select(h => new { h.HomeHelpID, h.HomeHelpName })); } } Now i am making it generic because there will be coming different types of Lists and i don't want to put if conditions this way i want to write generic code to handle any type of list. I came up with this way: private void HandleListProperty(object oldObject, object newObject, string difference, PropertyInfo prop) { var oldList = prop.GetValue(oldObject, null) as IList; var newList = prop.GetValue(newObject, null) as IList; var ListType = prop.PropertyType; var MyListInstance = Activator.CreateInstance(ListType); MyListInstance = oldList; } i am able to get the items in MyListInstance but as the type will come at runtime i am not getting how to write linq query to filter them, any ideah how to do.

    Read the article

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