with what property net method done c# reflection casting getproperty

what - Convierta a un tipo sobre la marcha en C#.NET



what can be done with reflection in c# (5)

Aquí hay otra manera de hacerlo, pero no estoy seguro

Sin soporte para tipos genéricos:

public void Foo(object obj,string propertyName,object value) { //Getting type of the property og object. Type type = obj.GetType().GetProperty(propertyName).PropertyType; obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null); }

Con soporte para tipos genéricos:

public void Foo(object obj,string propertyName,object value) { //Getting type of the property og object. Type type = obj.GetType().GetProperty(propertyName).PropertyType; if (type.IsGenericType) type = type.GetGenericArguments()[0]; obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null); }

Quiero convertir un objeto a un tipo que se asignará en tiempo de ejecución.

Por ejemplo, supongamos que tengo una función que asigna un valor de cadena (desde un TextBox or Dropdownlist ) a una Object.Property .

¿Cómo convertiría el valor al tipo correcto? Por ejemplo, podría ser un entero, una cadena o una enumeración.

Public void Foo(object obj,string propertyName,object value) { //Getting type of the property og object. Type t= obj.GetType().GetProperty(propName).PropertyType; //Now Setting the property to the value . //But it raise an error,because sometimes type is int and value is "2" //or type is enum (e.a: Gender.Male) and value is "Male" //Suppose that always the cast is valid("2" can be converted to int 2) obj.GetType().GetProperty(propName).SetValue(obj, value, null); }


No estoy seguro de que funcione, pero inténtalo:

public static T To<T>(this IConvertible obj) { return (T)Convert.ChangeType(obj, typeof(T)); } Public void Foo(object obj,string propertyName,object value) { Type t= obj.GetType().GetProperty(propName).PropertyType; obj.GetType().GetProperty(propName).SetValue(obj, value.To<t>(), null); }


Usé la función Convertir en C #. La forma en que estoy haciendo mi conversión es usando la reflexión .:

Type type = this.myObject.GetType(); if (type.Name == "MyObjectClass") { var Voucherrequest = (MyObjectClass)Convert.ChangeType(myObject, typeof(MyObjectClass));

Todo esto es asumiendo que sabes a qué tipo quieres convertir. Incluso puede hacer un cambio y tener varios tipos que desee reflejar también.


¡Un convertidor de tipo universal es lo que buscas! No es una tarea fácil ...

Pruebe este enfoque:

Convertidor de tipo universal

Puede en NuGet Install-Package UniversalTypeConverter

Además, ¿está usando Generics fuera de cuestión aquí? Facilitaría la solución si conoce al menos el tipo de destino de la conversión.


Necesitas usar la función Convert.ChangeType (...) (la entrada podría ser un objeto tan fácilmente ... Acabo de tener una versión de cadena precocida):

/// <summary> /// Sets a value in an object, used to hide all the logic that goes into /// handling this sort of thing, so that is works elegantly in a single line. /// </summary> /// <param name="target"></param> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> public static void SetPropertyValueFromString(this object target, string propertyName, string propertyValue) { PropertyInfo oProp = target.GetType().GetProperty(propertyName); Type tProp = oProp.PropertyType; //Nullable properties have to be treated differently, since we // use their underlying property to set the value in the object if (tProp.IsGenericType && tProp.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { //if it''s null, just set the value from the reserved word null, and return if (propertyValue == null) { oProp.SetValue(target, null, null); return; } //Get the underlying type property instead of the nullable generic tProp = new NullableConverter(oProp.PropertyType).UnderlyingType; } //use the converter to get the correct value oProp.SetValue(target, Convert.ChangeType(propertyValue, tProp), null); }