Search Results

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

Page 19/41 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • C# Calling Methods in Generic Classes

    - by aip.cd.aish
    I am extending the ImageBox control from EmguCV. The control's Image property can be set to anything implementing the IImage interface. All of the following implement this interface: Image<Bgr, Byte> Image<Ycc, Byte> Image<Hsv, Byte> Now I want to call the Draw method on the object of the above type (what ever it may be). The problem is when I access the Image property, the return type is IImage. IImage does not implement the Draw method, but all of the above do. I believe I can cast the object of type IImage to one of the above (the right one) and I can access the Draw method. But how do I know what the right one is? If you have a better way of doing this, please suggest that as well.

    Read the article

  • Extract Generic types from extended Generic

    - by Brigham
    I'm trying to refactor a class and set of subclasses where the M type does extend anything, even though we know it has to be a subclass of a certain type. That type is parametrized and I would like its parametrized types to be available to subclasses that already have values for M. Is there any way to define this class without having to include the redundant K and V generic types in the parameter list. I'd like to be able to have the compiler infer them from whatever M is mapped to by subclasses. public abstract class NewParametrized<K, V, M extends SomeParametrized<K, V>> { public void someMethodThatTakesKAndV(K k1, V v1) { } } In other words, I'd like the class declaration to look something like: public class NewParametrized<M extends SomeParametrized<K, V>> { And K and V's types would be inferred from the definition of M.

    Read the article

  • Type patterns and generic classes in Haskell

    - by finnsson
    I'm trying to understand type patterns and generic classes in Haskell but can't seem to get it. Could someone explain it in laymen's terms? In [1] I've read that "To apply functions generically to all data types, we view data types in a uniform manner: except for basic predefined types such as Float, IO, and ?, every Haskell data type can be viewed as a labeled sum of possibly labeled products." and then Unit, :*: and :+: are mentioned. Are all data types in Haskell automatically versions of the above mentioned and if so how do I figure out how a specific data type is represented in terms of :*:, etc? The users guide for generic classes (ch. 7.16) at haskell.org doesn't mention the predefined types but shouldn't they be handled in every function if the type patterns should be exhaustive? [1] Comparing Approaches to Generic Programming in Haskell, Ralf Hinze, Johan Jeuring, and Andres Löh

    Read the article

  • Can't Use Generic C# Class in Using Statement

    - by Eric J.
    I'm trying to use a generic class in a using statement but the compiler can't seem to treat it as implementing IDisposable. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Objects; namespace Sandbox { public sealed class UnitOfWorkScope<T> where T : ObjectContext, IDisposable, new() { public void Dispose() { } } public class MyObjectContext : ObjectContext, IDisposable { public MyObjectContext() : base("DummyConnectionString") { } #region IDisposable Members void IDisposable.Dispose() { throw new NotImplementedException(); } #endregion } public class Consumer { public void DoSomething() { using (new UnitOfWorkScope<MyObjectContext>()) { } } } } Compiler error is: Error 1 'Sandbox.UnitOfWorkScope<Sandbox.MyObjectContext>': type used in a using statement must be implicitly convertible to 'System.IDisposable' I implemented IDisposable on UnitOfWorkScope (and to see if that was the problem, also on MyObjectContext). What am I missing?

    Read the article

  • Generic property- specify the type at runtime

    - by Lirik
    I was reading a question on making a generic property, but I'm a little confused at by the last example from the first answer (I've included the relevant code below): You have to know the type at compile time. If you don't know the type at compile time then you must be storing it in an object, in which case you can add the following property to the Foo class: public object ConvertedValue { get { return Convert.ChangeType(Value, Type); } } That's seems strange: it's converting the value to the specified type, but it's returning it as an object when the value was stored as an object. Doesn't the returned object still require un-boxing? If it does, then why bother with the conversion of the type? I'm also trying to make a generic property whose type will be determined at run time: public class Foo { object Value {get;set;} Type ValType{get;set;} Foo(object value, Type type) { Value = value; ValType = type; } // I need a property that is actually // returned as the specified value type... public object ConvertedValue { get { return Convert.ChangeType(Value, ValType); } } } Is it possible to make a generic property? Does the return property still require unboxing after it's accessed?

    Read the article

  • Uses for static generic classes?

    - by Hightechrider
    What are the key uses of a Static Generic Class in C#? When should they be used? What examples best illustrate their usage? e.g. public static class Example<T> { public static ... } Since you can't define extension methods in them they appear to be somewhat limited in their utility. Web references on the topic are scarce so clearly there aren't a lot of people using them. Here's a couple:- http://ayende.com/Blog/archive/2005/10/05/StaticGenericClass.aspx http://stackoverflow.com/questions/686630/static-generic-class-as-dictionary

    Read the article

  • .net runtime type casting when using reflection

    - by Mike
    I have need to cast a generic list of a concrete type to a generic list of an interface that the concrete types implement. This interface list is a property on an object and I am assigning the value using reflection. I only know the value at runtime. Below is a simple code example of what I am trying to accomplish: public void EmployeeTest() { IList<Employee> initialStaff = new List<Employee> { new Employee("John Smith"), new Employee("Jane Doe") }; Company testCompany = new Company("Acme Inc"); //testCompany.Staff = initialStaff; PropertyInfo staffProperty = testCompany.GetType().GetProperty("Staff"); staffProperty.SetValue(testCompany, (staffProperty.PropertyType)initialStaff, null); } Classes are defined like so: public class Company { private string _name; public string Name { get { return _name; } set { _name = value; } } private IList<IEmployee> _staff; public IList<IEmployee> Staff { get { return _staff; } set { _staff = value; } } public Company(string name) { _name = name; } } public class Employee : IEmployee { private string _name; public string Name { get { return _name; } set { _name = value; } } public Employee(string name) { _name = name; } } public interface IEmployee { string Name { get; set; } } Any thoughts? I am using .NET 4.0. Would the new covariant or contravariant features help? Thanks in advance.

    Read the article

  • How to use List<T>.Find() on a simple collection that does not implement Find()?

    - by Bilal
    Hi, I want to use List.Find() on a simple collection that does not implement Find(). The naive way I thought of, is to just wrap it with a list and execute .Find(), like this: ICollection myCows = GetAllCowsFromFarm(); // whatever the collection impl. is... var steak = new List<Cow>(myCows).Find(moo => moo.Name == "La Vache qui Rit"); Now, 1st of all I'd like to know, C#-wise, what is the cost of this wrapping? Is it still faster to 'for' this collection the traditional way? Second, is there a better straightforward way elegantly use that .Find()? Cheers!

    Read the article

  • XML Serializing a class with a Dictionary<string, List<string>> object

    - by Matt
    Is it possible to implement IXmlSerializable and in my XML file capture an object of type Dictionary ? I have the following public class coolio : IXmlSerializable { private int a; private bool b; private string c; private Dictionary<string, List<string>> coco; public coolio(int _a, bool _b, string _c, Dictionary<string, List<string>> _coco) { a=_a; b=_b; c=_c; coco=_coco; } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void WriteXml(XmlWriter writer) { const string myType = "coolio"; writer.WriteStartElement(myType); writer.WriteAttributeString("a", a.ToString()); writer.WriteAttributeString("b", b.ToString()); writer.WriteAttributeString("c", c); // How do I add a subelement for Dictionary<string, List<string>> coco? writer.WriteEndElement(); } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() != XmlNodeType.Element || reader.LocalName != "coolio") return; a= int.Parse(reader["a"]); b = bool.Parse(reader["b"]); c= reader["c"]; // How do I read subelement into Dictionary<string, List<string>> coco? } } But I am stumped as to how I could add the Dictionary (XML seriliazed to my XML file)

    Read the article

  • Using C# Type as generic

    - by I Clark
    I'm trying to create a generic list from a specific Type that is retrieved from elsewhere: Type listType; // Passed in to function, could be anything var list = _service.GetAll<listType>(); However I get a build error of: The type or namespace name 'listType' could not be found (are you missing a using directive or an assembly reference?) Is this even possible or am I setting foot onto C# 4 Dynamic territory? As a background: I want to automatically load all lists with data from the repository. The code below get's passed a Form Model whose properties are iterated for any IEnum (where T inherits from DomainEntity). I want to fill the list with objects of the Type the list made of from the repository. public void LoadLists(object model) { foreach (var property in model.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty)) { if (IsEnumerableOfNssEntities(property.PropertyType)) { var listType = property.PropertyType.GetGenericArguments()[0]; var list = _repository.Query<listType>().ToList(); property.SetValue(model, list, null); } } }

    Read the article

  • Trying to put a generic MyObj<T, U> into an IList where U can be different between objects

    - by Sergio Romero
    I have the following class definition: public interface IItem{} public class FirstObject<T, U> : IItem { public U SomeProperty { get; private set; } } IList<IItem> myList = new List<IItem>(); I did it like this because U can be of different types. Now I want to iterate the list and get my items back, the problem is that I do not know how to cast them back to their original type so I can read the value of SomeProperty. Thanks for your help.

    Read the article

  • How can i convert this to a factory/abstract factory?

    - by Amitd
    I'm using MigraDoc to create a pdf document. I have business entities similar to the those used in MigraDoc. public class Page{ public List<PageContent> Content { get; set; } } public abstract class PageContent { public int Width { get; set; } public int Height { get; set; } public Margin Margin { get; set; } } public class Paragraph : PageContent{ public string Text { get; set; } } public class Table : PageContent{ public int Rows { get; set; } public int Columns { get; set; } //.... more } In my business logic, there are rendering classes for each type public interface IPdfRenderer<T> { T Render(MigraDoc.DocumentObjectModel.Section s); } class ParagraphRenderer : IPdfRenderer<MigraDoc.DocumentObjectModel.Paragraph> { BusinessEntities.PDF.Paragraph paragraph; public ParagraphRenderer(BusinessEntities.PDF.Paragraph p) { paragraph = p; } public MigraDoc.DocumentObjectModel.Paragraph Render(MigraDoc.DocumentObjectModel.Section s) { var paragraph = s.AddParagraph(); // add text from paragraph etc return paragraph; } } public class TableRenderer : IPdfRenderer<MigraDoc.DocumentObjectModel.Tables.Table> { BusinessEntities.PDF.Table table; public TableRenderer(BusinessEntities.PDF.Table t) { table =t; } public MigraDoc.DocumentObjectModel.Tables.Table Render(Section obj) { var table = obj.AddTable(); //fill table based on table } } I want to create a PDF page as : var document = new Document(); var section = document.AddSection();// section is a page in pdf var page = GetPage(1); // get a page from business classes foreach (var content in page.Content) { //var renderer = createRenderer(content); // // get Renderer based on Business type ?? // renderer.Render(section) } For createRenderer() i can use switch case/dictionary and return type. How can i get/create the renderer generically based on type ? How can I use factory or abstract factory here? Or which design pattern better suits this problem?

    Read the article

  • Use component id in Castle Windsor generic object configuration

    - by ChoccyButton
    2 questions in one, but very much related. Is it possible with Castle Windsor to resolve a configuration entry such as - Assembly.Namespace.Object1`2[[${ComponentId1}],[${ComponentId2}]], Assembly Where ComponentId1 and ComponentId2 are defined as components. Castle Windsor doesn't seem to be resolving the ComponentId, it is just looking for ComponentId1 in the Castle.Windsor assembly. The second question comes in to play if you can't do the first question. If you have to use a full assembly reference instead of a ComponentId, how can you pass any parameters to the object being created? eg to set ComponentId1.Field1 = "blah", or pass something to the constructor of ComponentId1 Hope that makes sense Update - Following the request for code I've knocked together the following - Objects public class Wrapper<T, T1> where T : ICollector where T1:IProcessor { private T _collector; private T1 _processor; public Wrapper(T collector, T1 processor) { _collector = collector; _processor = processor; } public void GetData() { _collector.CollectData(); _processor.ProcessData(); } } public class Collector1 : ICollector { public void CollectData() { Console.WriteLine("Collecting data from Collector1 ..."); } } public class Processor1 : IProcessor { public void ProcessData() { Console.WriteLine("Processing data from Processor1 ..."); } } repeated so 3 of each type of object in the example Config <components> <component id="Collector1" service="CastleWindsorPlay.ICollector, CastleWindsorPlay" type="CastleWindsorPlay.Collector1, CastleWindsorPlay"/> <component id="Collector2" service="CastleWindsorPlay.ICollector, CastleWindsorPlay" type="CastleWindsorPlay.Collector2, CastleWindsorPlay"/> <component id="Collector3" service="CastleWindsorPlay.ICollector, CastleWindsorPlay" type="CastleWindsorPlay.Collector3, CastleWindsorPlay"/> <component id="Processor1" service="CastleWindsorPlay.IProcessor, CastleWindsorPlay" type="CastleWindsorPlay.Processor1, CastleWindsorPlay"/> <component id="Processor2" service="CastleWindsorPlay.IProcessor, CastleWindsorPlay" type="CastleWindsorPlay.Processor2, CastleWindsorPlay"/> <component id="Processor3" service="CastleWindsorPlay.IProcessor, CastleWindsorPlay" type="CastleWindsorPlay.Processor3, CastleWindsorPlay"/> <component id="Wrapper1" type="CastleWindsorPlay.Wrapper`2[[CastleWindsorPlay.Collector1, CastleWindsorPlay],[CastleWindsorPlay.Processor3, CastleWindsorPlay]], CastleWindsorPlay" /> </components> Instantiation var wrapper = (Wrapper<ICollector, IProcessor>) container.Resolve("Wrapper1"); wrapper.GetData(); This brief example errors with this error message though - Can't create component 'Wrapper1' as it has dependencies to be satisfied. Wrapper1 is waiting for the following dependencies: Services: - CastleWindsorPlay.Collector1 which was not registered. - CastleWindsorPlay.Processor3 which was not registered. The curious part about this is that I can get it to resolve Collector1 and Processor3 individually before the call to the wrapper, but the wrapper still can't see them. This is a basic example, the next thing I'd like to be able to do is when instantiating the Wrapper, set a property on the collector and/or processor. So it could be something like Collector.Id = 10, but set in the config where the wrapper is defined. Setting against the Collector component definition wouldn't work as I'd want to be able to instantiate multiple copies of each Collector, using different Id's Update 2 What I'm actually trying to do is have - <components> <component id="Wrapper1" type="CastleWindsorPlay.Wrapper`2[${Collector1}(id=1)],[${Processor3}]], CastleWindsorPlay" /> <component id="Wrapper2" type="CastleWindsorPlay.Wrapper`2[${Collector1}(id=3)],[${Processor3}]], CastleWindsorPlay" /> </components> Then have another object defined as <component id="Manager" type="CastleWindsorPlay.Manager,CastleWindsorPlay"> <parameters> <wrappers> <array> <item>${Wrapper1}</item> <item>${Wrapper2}</item> </array> </wrappers> </parameters> Then finally in code just be able to call - var manager = (Manager)container.Resolve("Manager"); This should return the manager object, with an array of wrappers populated and the wrappers configured with the correct Collector and Convertor. I know there are errors in the Castle config here, that's why I'm asking the question, I don't know how to set the config up to do what I'm after, or even if it's possible to do it in Castle Windsor

    Read the article

  • Scala type inference failure on "? extends" in Java code

    - by oxbow_lakes
    I have the following simple Java code: package testj; import java.util.*; public class Query<T> { private static List<Object> l = Arrays.<Object>asList(1, "Hello", 3.0); private final Class<? extends T> clazz; public static Query<Object> newQuery() { return new Query<Object>(Object.class); } public Query(Class<? extends T> clazz) { this.clazz = clazz; } public <S extends T> Query<S> refine(Class<? extends S> clazz) { return new Query<S>(clazz); } public List<T> run() { List<T> r = new LinkedList<T>(); for (Object o : l) { if (clazz.isInstance(o)) r.add(clazz.cast(o)); } return r; } } I can call this from Java as follows: Query<String> sq = Query.newQuery().refine(String.class); //NOTE NO <String> But if I try and do the same from Scala: val sq = Query.newQuery().refine(classOf[String]) I get the following error: error: type mismatch found :lang.this.class[scala.this.Predef.String] required: lang.this.class[?0] forSome{ type ?0 <: ? } val sq = Query.newQuery().refine(classOf[String]) This is only fixed by the insertion of the correct type parameter! val sq = Query.newQuery().refine[String](classOf[String]) Why can't scala infer this from my argument? Note I am using Scala 2.7

    Read the article

  • Typed DefaultListModel to avoid casting

    - by Thomas R.
    Is there a way in java to have a ListModel that only accepts a certain type? What I'm looking for is something like DefaultListModel<String> oder TypedListModel<String>, because the DefaultListModel only implements addElement(Object obj) and get(int index) which returns Object of course. That way I always have to cast from Object to e.g. String and there is no guarantee that there are only strings in my model, even though I'd like to enforce that. Is this a flaw or am I using list models the wrong way?

    Read the article

  • Type-safe mapping from Class<T> to Thing<T>

    - by Joonas Pulakka
    I want to make a map-kind of container that has the following interface: public <T> Thing<T> get(Class<T> clazz); public <T> void put(Class<T> clazz, Thing<T> thing); The interesting point is that the Ts in each Class<T><- Thing<T> pair is the same T, but the container should be able to hold many different types of pairs. Initially I tried a (Hash)Map. But, for instance, Map<Class<T>, Thing<T>> is not right, because then T would be same T for all pairs in that map. Of course, Map<Class<?>, Thing<?>> works, but then I don't have type-safety guarantees so that when I get(String.class), I can't be sure that I get a Thing<String> instance back. Is there a way to accomplish the kind of type safety that I'm looking for?

    Read the article

  • How am I able to create A List<T> containing a generic Interface?

    - by Conrad Clark
    I have a List which must contain IInteract Objects. But IInteract is a generic interface which requires 2 type arguments. My main idea is iterate through a list of Objects and "Interact" one with another if they didn't interact yet. So i have this object List<IObject> WorldObjects = new List<IObject>(); and this one: private List<IInteract> = new List<IInteract>(); Except I can't compile the last line because IInteract requires 2 type arguments. But I don't know what the arguments are until I add them. I could add interactions between Objects of Type A and A... or Objects of Type B and C. I want to create "Interaction" classes which do something with the "acting" object and the "target" object, but I want them to be independent from the objects... so I could add an Interaction between for instance... "SuperUltraClass" and... an "integer". Am I using the wrong approach?

    Read the article

  • Cast Object to Generic List

    - by CrazyJoe
    I have 3 generict type list. List<Contact> = new List<Contact>(); List<Address> = new List<Address>(); List<Document> = new List<Document>(); And save it on a variable with type object. Now i nedd do Cast Back to List to perfom a foreach, some like this: List<Contact> = (List<Contact>)obj; But obj content change every time, and i have some like this: List<???> = (List<???>)obj; I have another variable holding current obj Type: Type t = typeof(obj); Can i do some thing like that??: List<t> = (List<t>)obj; Obs: I no the current type in the list but i need to cast , and i dont now another form instead: List<Contact> = new List<Contact>(); Help Plz!!!

    Read the article

  • Constraint Validation

    - by tanuja
    I am using javax.validation.Validator and relevant classes for annotation based validation. Configuration<?> configuration = Validation.byDefaultProvider().configure(); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<ValidatableObject>> constraintViolations = validator.validate(o); for (ConstraintViolation<ValidatableObject> value : constraintViolations) { List< Class< ? extends ConstraintValidator< ? extends Annotation,?>>> list = value.getConstraintDescriptor().getConstraintValidatorClasses(); } I get a compilation error stating: Type mismatch: cannot convert from List< Class< ? extends ConstraintValidator< capture#4-of ?,? to List< Class< ? extends ConstraintValidator< ? extends Annotation,? What am I missing?

    Read the article

  • Why is Delphi unable to infer the type for a parameter TEnumerable<T>?

    - by deepc
    Consider the following declaration of a generic utility class in Delphi 2010: TEnumerableUtils = class public class function InferenceTest<T>(Param: T): T; class function Count<T>(Enumerable: TEnumerable<T>): Integer; overload; class function Count<T>(Enumerable: TEnumerable<T>; Filter: TPredicate<T>): Integer; overload; end; Somehow the compiler type inference seems to have problems here: var I: Integer; L: TList<Integer>; begin TEnumerableUtils.InferenceTest(I); // no problem here TEnumerableUtils.Count(L); // does not compile: E2250 There is no overloaded version of 'Count' that can be called with these arguments TEnumerableUtils.Count<Integer>(L); // compiles fine end; The first call works as expected and T is correctly inferred as Integer. The second call does not work, unless I also add <Integer -- then it works, as can be seen in the third call. Am I doing something wrong or is the type inference in Delphi just not supporting this (I don't think it is a problem in Java which is why expected it to work in Delphi, too).

    Read the article

  • Deserialize Stream to List<T> or any other type

    - by Sam
    Attempting to deserialize a stream to List<T> (or any other type) and am failing with the error: The type arguments for method 'Foo.Deserialize<T>(System.IO.Stream)' cannot be inferred from the usage. Try specifying the type arguments explicitly. This fails: public static T Deserialize<T>(this Stream stream) { BinaryFormatter bin = new BinaryFormatter(); return (T)bin.Deserialize(stream); } But this works: public static List<MyClass.MyStruct> Deserialize(this Stream stream) { BinaryFormatter bin = new BinaryFormatter(); return (List<MyClass.MyStruct>)bin.Deserialize(stream); } or: public static object Deserialize(this Stream stream) { BinaryFormatter bin = new BinaryFormatter(); return bin.Deserialize(stream); } Is it possible to do this without casting, e.g. (List<MyStruct>)stream.Deserialize()?

    Read the article

  • Generic InBetween Function.

    - by Luiscencio
    I am tired of writing x > min && x < max so i wawnt to write a simple function but I am not sure if I am doing it right... actually I am not cuz I get an error: bool inBetween<T>(T x, T min, T max) where T:IComparable { return (x > min && x < max); } errors: Operator '>' cannot be applied to operands of type 'T' and 'T' Operator '<' cannot be applied to operands of type 'T' and 'T' may I have a bad understanding of the where part in the function declaring note: for those who are going to tell me that I will be writing more code than before... think on readability =) any help will be appreciated EDIT deleted cuz it was resolved =) ANOTHER EDIT so after some headache I came out with this (ummm) thing following @Jay Idea of extreme readability: public static class test { public static comparision Between<T>(this T a,T b) where T : IComparable { var ttt = new comparision(); ttt.init(a); ttt.result = a.CompareTo(b) > 0; return ttt; } public static bool And<T>(this comparision state, T c) where T : IComparable { return state.a.CompareTo(c) < 0 && state.result; } public class comparision { public IComparable a; public bool result; public void init<T>(T ia) where T : IComparable { a = ia; } } } now you can compare anything with extreme readability =) what do you think.. I am no performance guru so any tweaks are welcome

    Read the article

  • Cannot call action method 'System.Web.Mvc.PartialViewResult Foo[T](T)' on controller 'Controller' be

    - by MedicineMan
    Cannot call action method 'System.Web.Mvc.PartialViewResult FooT' on controller 'Controller' because the action method is a generic method <% Html.RenderAction("Foo", model = Model}); %> Is there a workaround for this limitation on ASP MVC 2? I would really prefer to use a generic. The workaround that I have come up with is to change the model type to be an object. It works, but is not preferred: public PartialViewResult Foo<T>(T model) where T : class { // do stuff }

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >