Search Results

Search found 46727 results on 1870 pages for 'system reflection'.

Page 8/1870 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Determining if a .NET type is dynamic (created using Reflection.Emit)

    - by Diego Mijelshon
    While the .NET 4 framework provides the Assembly.IsDynamic method, that's not the case with .NET 2.0/3.5. The use case is simple: for logging purposes, I want to determine the underlying type name of an entity that might be wrapped by a dynamic proxy without having any references to NHibernate or Castle (which know about the proxy) For example, I might have a CatProxYadaYada, but I'm interested in Cat. What's the easiest way to get that type? I was thinking of this skeleton: var type = obj.GetType(); while (IsProxy_Dynamic_Whatever(obj)) type = type.BaseType; return type;

    Read the article

  • Reflection and changing a variables type at runtime?

    - by james-west
    Hi I'm trying to create an object Of a specific type. I've got the following code, but it fails because it can't cast the new table object to the one that is already defined. I need table to start of an IEnumerable type so I can't declare is an object. Public sub getTable(ByVal t as Type) Dim table As Table(Of Object) Dim tableType As Type = GetType(Table(Of )).MakeGenericType(t) table = FormatterServices.GetUninitializedObject(tableType) End sub So in short - is there a way of changing a variable type at runtime? (or a better way of doing what I'm doing) Thanks in advance. James

    Read the article

  • Extension method using Reflection to Sort

    - by Xavier
    I implemented an extension "MyExtensionSortMethod" to sort collections (IEnumerate). This allows me to replace code such as 'entities.OrderBy( ... ).ThenByDescending( ...)' by 'entities.MyExtensionSortMethod()' (no parameter as well). Here is a sample of implementation: //test function function Test(IEnumerable<ClassA> entitiesA,IEnumerable<ClassB> entitiesB ) { //Sort entitiesA , based on ClassA MySort method var aSorted = entitiesA.MyExtensionSortMethod(); //Sort entitiesB , based on ClassB MySort method var bSorted = entitiesB.MyExtensionSortMethod(); } //Class A definition public classA: IMySort<classA> { .... public IEnumerable<classA> MySort(IEnumerable<classA> entities) { return entities.OrderBy( ... ).ThenBy( ...); } } public classB: IMySort<classB> { .... public IEnumerable<classB> MySort(IEnumerable<classB> entities) { return entities.OrderByDescending( ... ).ThenBy( ...).ThenBy( ... ); } } //extension method public static IEnumerable<T> MyExtensionSortMethod<T>(this IEnumerable<T> e) where T : IMySort<T>, new() { //the extension should call MySort of T Type t = typeof(T); var methodInfo = t.GetMethod("MySort"); //invoke MySort var result = methodInfo.Invoke(new T(), new object[] {e}); //Return return (IEnumerable < T >)result; } public interface IMySort<TEntity> where TEntity : class { IEnumerable<TEntity> MySort(IEnumerable<TEntity> entities); } However, it seems a bit complicated compared to what it does so I was wondering if they were another way of doing it?

    Read the article

  • Trouble Emitting Object Array using Reflection.Emit

    - by JoeGeeky
    I am trying to Emit what I thought would be a simple object array that would result in code similar to the below example object[] parameters = new object[] { a, b, }; When I write the above code in C# using VS, I get the following IL. As expected this works. .locals init ( [0] object[] parameters, [1] object[] CS$0$0000) However, when I try and Emit IL directly, I only ever get a one index init array. Can someone help tell me where I've gone wrong here? Here is the Emit code I'm using: int arraySize = 2; LocalBuilder paramValues = ilGenerator.DeclareLocal(typeof(object[])); paramValues.SetLocalSymInfo("parameters"); ilGenerator.Emit(OpCodes.Ldc_I4_S, arraySize); ilGenerator.Emit(OpCodes.Newarr, typeof(object)); ilGenerator.Emit(OpCodes.Stloc, paramValues); Here is the resulting IL: .locals init ( [0] object[] objArray) The rest of the resulting IL is identical between the two solutions, but for some reason the .locals init is different.

    Read the article

  • BindingList<T> and reflection!

    - by Aren B
    Background Working in .NET 2.0 Here, reflecting lists in general. I was originally using t.IsAssignableFrom(typeof(IEnumerable)) to detect if a Property I was traversing supported the IEnumerable Interface. (And thus I could cast the object to it safely) However this code was not evaluating to True when the object is a BindingList<T>. Next I tried to use t.IsSubclassOf(typeof(IEnumerable)) and didn't have any luck either. Code /// <summary> /// Reflects an enumerable (not a list, bad name should be fixed later maybe?) /// </summary> /// <param name="o">The Object the property resides on.</param> /// <param name="p">The Property We're reflecting on</param> /// <param name="rla">The Attribute tagged to this property</param> public void ReflectList(object o, PropertyInfo p, ReflectedListAttribute rla) { Type t = p.PropertyType; //if (t.IsAssignableFrom(typeof(IEnumerable))) if (t.IsSubclassOf(typeof(IEnumerable))) { IEnumerable e = p.GetValue(o, null) as IEnumerable; int count = 0; if (e != null) { foreach (object lo in e) { if (count >= rla.MaxRows) break; ReflectObject(lo, count); count++; } } } } The Intent I want to basically tag lists i want to reflect through with the ReflectedListAttribute and call this function on the properties that has it. (Already Working) Once inside this function, given the object the property resides on, and the PropertyInfo related, get the value of the property, cast it to an IEnumerable (assuming it's possible) and then iterate through each child and call ReflectObject(...) on the child with the count variable.

    Read the article

  • Loading remote assembly from the webservice with reflection

    - by Myat Htut
    I am using Assembly.LoadFrom within a web service to load assemblies from a web site. but the problem is it is in the virutal directory and the server.mappath parses the url like \share\mydll.dll and loadform method failed. Is there anyway to reference dll from the remote location? I've tried passing the url (http:\localhost\downloadable\mydll.dll) and again it got "Could not load file or assembly 'http:\localhost\downloadable\mydll.dll' or one of its dependencies. HTTP download of assemblies has been disabled for this appdomain. (Exception from HRESULT: 0x80131048)"

    Read the article

  • C# reflection, cloning

    - by Enriquev
    Say I have this class Myclass that contains this method: public class MyClass { public int MyProperty { get; set; } public int MySecondProperty { get; set; } public MyOtherClass subClass { get; set; } public object clone<T>(object original, T emptyObj) { FieldInfo[] fis = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); object tempMyClass = Activator.CreateInstance(typeof(T)); foreach (FieldInfo fi in fis) { if (fi.FieldType.Namespace != original.GetType().Namespace) fi.SetValue(tempMyClass, fi.GetValue(original)); else fi.SetValue(tempMyClass, this.clone(fi.GetValue(original), fi.GetValue(original))); } return tempMyClass; } } Then this class: public class MyOtherClass { public int MyProperty777 { get; set; } } when I do this: MyClass a = new MyClass { MyProperty = 1, MySecondProperty = 2, subClass = new MyOtherClass() { MyProperty777 = -1 } }; MyClass b = a.clone(a, a) as MyClass; how come on the second call to clone, T is of type object and not of type MyOtherClass

    Read the article

  • C# reflection instantiation

    - by NickLarsen
    I am currently trying to create a generic instance factory for which takes an interface as the generic parameter (enforced in the constructor) and then lets you get instantiated objects which implement that interface from all types in all loaded assemblies. The current implementation is as follows:     public class InstantiationFactory     {         protected Type Type { get; set; }         public InstantiationFactory()         {             this.Type = typeof(T);             if (!this.Type.IsInterface)             {                 // is there a more descriptive exception to throw?                 throw new ArgumentException(/* Crafty message */);             }         }         public IEnumerable GetLoadedTypes()         {             // this line of code found in other stack overflow questions             var types = AppDomain.CurrentDomain.GetAssemblies()                 .SelectMany(a = a.GetTypes())                 .Where(/* lambda to identify instantiable types which implement this interface */);             return types;         }         public IEnumerable GetImplementations(IEnumerable types)         {             var implementations = types.Where(/* lambda to identify instantiable types which implement this interface */                 .Select(x = CreateInstance(x));             return implementations;         }         public IEnumerable GetLoadedImplementations()         {             var loadedTypes = GetLoadedTypes();             var implementations = GetImplementations(loadedTypes);             return implementations;         }         private T CreateInstance(Type type)         {             T instance = default(T);             var constructor = type.GetConstructor(Type.EmptyTypes);             if (/* valid to instantiate test */)             {                 object constructed = constructor.Invoke(null);                 instance = (T)constructed;             }             return instance;         }     } It seems useful to me to have my CreateInstance(Type) function implemented as an extension method so I can reuse it later and simplify the code of my factory, but I can't figure out how to return a strongly typed value from that extension method. I realize I could just return an object:     public static class TypeExtensions     {         public object CreateInstance(this Type type)         {             var constructor = type.GetConstructor(Type.EmptyTypes);             return /* valid to instantiate test */ ? constructor.Invoke(null) : null;         }     } Is it possible to have an extension method create a signature per instance of the type it extends? My perfect code would be this, which avoids having to cast the result of the call to CreateInstance():     Type type = typeof(MyParameterlessConstructorImplementingType);     MyParameterlessConstructorImplementingType usable = type.CreateInstance();

    Read the article

  • Subscribing to a ObservableCollection via reflection

    - by Julian Lettner
    How can I subscribe to a ObservableCollection<??> without knowing the element type of the collection? Is there a way to do this without too many 'magic strings'? This is a question for the .NET version 3.5. I think 4.0 would make my life much easier, right? Type type = collection.GetType(); if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ObservableCollection<>)) { // I cannot cast the collection here ObservableCollection<object> x = collection; } Thanks for your time.

    Read the article

  • Execute method with Action<T> argument using Reflection

    - by JGr
    How can i create a Action method to use as a argument to the following function? public void When(Action<T> action) { if (internalValue != null) action(internalValue); } I have the MethodInfo on the method, and the parameter type like so: var methods = value.GetType().GetMethods(); MethodInfo mInfo = methods.First(method => method.Name == "When"); Type parameterType = (mInfo.GetParameters()[0]).ParameterType; But after that i have no idea how to make the actual Action method to pass as argument, i also do not know how to define the Action method body.

    Read the article

  • Typecast to a type from just the string representation of the type name

    - by Water Cooler v2
    sTypeName = ... //do some string stuff here to get the name of the type /* The Assembly.CreateInstance function returns a type of System.object. I want to type cast it to the type whose name is sTypeName. assembly.CreateInstance(sTypeName) So, in effect I want to do something like: */ assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName); How do I do that? And, what do I take on the left side of the assignment expression, assuming this is C# 2.0. I don't have the var keyword.

    Read the article

  • C# Reflection and Getting Properties

    - by Nathan
    I have the following dummy class structure and I am trying to find out how to get the properties from each instance of the class People in PeopleList. I know how to get the properties from a single instance of People but can't for the life of me figure out how to get it from PeopleList. I am sure this is really straightforward but can someone point me in the right direction? public class Example { public class People { private string _name; public string Name { get { return _name; } set { _name = value; } } private int _age; public int Age { get { return _age; } set { _age = value; } } public People() { } public People(string name, int age) { this._name = name; this._age = age; } } public class PeopleList : List<People> { public static void DoStuff() { PeopleList newList = new PeopleList(); // Do some stuff newList.Add(new People("Tim", 35)); } } }

    Read the article

  • c# Reflection - Find the Generic Type of a Collection

    - by Andy Clarke
    Hi, I'm reflecting a property 'Blah' its Type is ICollection public ICollection<string> Blah { get; set; } private void button1_Click(object sender, RoutedEventArgs e) { var pi = GetType().GetProperty("Blah"); MessageBox.Show(pi.PropertyType.ToString()); } This gives me (as you'd expect!) ICollection<string> ... But really I want to get the collection type i.e. ICollection (rather than ICollection<string>) - does anyone know how i'd do this please?

    Read the article

  • Comparing Object properties using reflection

    - by Kumar
    I have two classes Address and Employee as follows: public class Address { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } public class Employee { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public Address EmployeeAddress { get; set; } } I have two employee instances as follows: var emp1Address = new Address(); emp1Address.AddressLine1 = "Microsoft Corporation"; emp1Address.AddressLine2 = "One Microsoft Way"; emp1Address.City = "Redmond"; emp1Address.State = "WA"; emp1Address.Zip = "98052-6399"; var emp1 = new Employee(); emp1.FirstName = "Bill"; emp1.LastName = "Gates"; emp1.EmployeeAddress = emp1Address; var emp2Address = new Address(); emp2Address.AddressLine1 = "Gates Foundation"; emp2Address.AddressLine2 = "One Microsoft Way"; emp2Address.City = "Redmond"; emp2Address.State = "WA"; emp2Address.Zip = "98052-6399"; var emp2 = new Employee(); emp2.FirstName = "Melinda"; emp2.LastName = "Gates"; emp2.EmployeeAddress = emp2Address; Now how can I write a method which compares these two employees and returns the list of properties which have different values. So in this example I would like the result to be FirstName and Address.AddressLine1 .

    Read the article

  • Reflection & Parameters in C#

    - by Jim
    Hello, I'm writing an application that runs "things" to a schedule. Idea being that the database contains assembly, method information and also the parameter values. The timer will come along, reflect the method to be run, add the parameters and then execute the method. Everything is fine except for the parameters. So, lets say the method accepts an ENUM of CustomerType where CustomerType has two values of CustomerType.Master and CustomerType.Associate. EDIT I don't the type of parameter that will be getting passed in. ENUM used as an example END OF EDIT We want to run Method "X" and pass in parameter "CustomerType.Master". In the database, there will be a varchar entry of "CustomerType.Master". How do I convert the string "CustomerType.Master" into a type of CustomerType with a value of "Master" generically? Thanks in advance, Jim

    Read the article

  • Getting fields of a class through reflection

    - by Water Cooler v2
    I've done it a gazillion times in the past and successfully so. This time, I'm suffering from lapses of amnesia. So, I am just trying to get the fields on an object. It is an embarrassingly simple and stupid piece of code that I am writing in a test solution before I do something really useful in production code. Strangely, the GetFieldsOf method reports a zero length array on the "Amazing" class. Help. class Amazing { private NameValueCollection _nvc; protected NameValueCollection _myDict; } private static FieldInfo[] GetFieldsOf(string className, string nameSpace = "SomeReflection") { Type t; return (t = Assembly.GetExecutingAssembly().GetType( string.Format("{0}.{1}", nameSpace, className) )) == null ? null : t.GetFields(); }

    Read the article

  • Generics and reflection in Java

    - by Ragesh
    This is probably a very basic question, but I'm really new to generics in Java and I'm having a hard time altering my thought process from the way things are done in C#, so bear with me. I'm trying to build a generic repository in Java. I've created an IRepository interface that looks like this: public interface IRepository<T extends IEntity> And a Repository class that looks like this: public class Repository<T extends IEntity> implements IRepository<T> Now, from within the constructor of my Repository class, I'd like to be able to "divine" the exact type of T. For example, if I instantiated a repository like this: IRepository<MyClass> repo = new Repository<MyClass>(); I'd like to know that T is actually MyClass. This is trivial in C#, but obviously generics are a totally different beast in Java and I can't seem to find anything that would help me do this.

    Read the article

  • Reflection and Generics get value of property

    - by GigaPr
    Hi i am trying to implement a generic method which allows to output csv file public static void WriteToCsv<T>(List<T> list) where T : new() { const string attachment = "attachment; filename=PersonList.csv"; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.AddHeader("content-disposition", attachment); HttpContext.Current.Response.ContentType = "text/csv"; HttpContext.Current.Response.AddHeader("Pragma", "public"); bool isFirstRow = true; foreach (T item in list) { //Get public properties PropertyInfo[] propertyInfo = item.GetType().GetProperties(); while (isFirstRow) { WriteColumnName(propertyInfo); isFirstRow = false; } Type type = typeof (T); StringBuilder stringBuilder = new StringBuilder(); foreach (PropertyInfo info in propertyInfo) { //string value ???? I am trying to get the value of the property info for the item object } HttpContext.Current.Response.Write(stringBuilder.ToString()); HttpContext.Current.Response.Write(Environment.NewLine); } HttpContext.Current.Response.End(); } but I am not able to get the value of the object's property Any suggestion? Thanks

    Read the article

  • Reflection: How to get the underlying type of a by-ref type

    - by Qwertie
    I was surprised to learn that "ref" and "out" parameters are not marked by a special attribute, despite the existence of ParameterInfo.IsOut, ParameterInfo.IsIn (both of which are always false as far as I can see), ParameterAttributes.In and ParameterAttributes.Out. Instead, "ref" parameters are actually represented by a special kind of "Type" object and "out" parameters are just ref parameters with an additional attribute (what kind of attribute I don't yet know). Anyway, to make a by-ref argument you call Type.MakeByRefType(), but my question is, if you already have a by-ref type, how do you get back to the original Type? Hint: it's not UnderlyingSystemType: Type t = typeof(int); Console.WriteLine(t.MakeByRefType().UnderlyingSystemType==t); // FALSE

    Read the article

  • How to dynamically use the PropertyType reflection attribute to create a respective typed Function<

    - by vsj
    I want to use type returned by PropertyType to create a typed function. I found this similiar http://stackoverflow.com/questions/914578/using-type-returned-by-type-gettype-in-c but this mentions how to create a list but does not mention how we can create a Func<. Please help me out. Pseudocode: PropertyInfo inf = typeof(SomeClass).GetProperty("PropertyName"); Type T=inf.PropertyType; Expression<Func<SomeClass,T>> le = GetPropertyOrFieldByName<SomeClass, T>("PropertyName");

    Read the article

  • C# Reflection Question

    - 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

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >