Ich möchte ein Objekt in einen Typ konvertieren, der zur Laufzeit zugewiesen wird.
Angenommen, ich habe eine Funktion, die einem TextBox or Dropdownlist
einen Zeichenfolgewert (aus einem Object.Property
) zuweist.
Wie würde ich den Wert in den richtigen Typ konvertieren? Zum Beispiel kann es eine ganze Zahl, eine Zeichenfolge oder eine Aufzählung sein.
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);
}
Sie müssen die Funktion Convert.ChangeType (...) verwenden (die Eingabe könnte genauso einfach ein Objekt sein ... Ich hatte nur eine String-Version vorgebacken):
/// <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);
}
Ein universeller Typkonverter ist das, wonach Sie suchen!? Keine leichte Leistung ..
Versuchen Sie diesen Ansatz:
Sie können in NuGet Install-Package UniversalTypeConverter
Ist die Verwendung von Generics
hier nicht in Frage? Dies würde die Lösung erleichtern, wenn Sie zumindest den Zieltyp der Konvertierung kennen.
Hier haben Sie eine andere Möglichkeit, aber ich bin mir nicht sicher
Ohne Unterstützung für generische Typen:
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);
}
Mit Unterstützung für generische Typen:
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);
}
Ich habe die Konvertierungsfunktion in C # verwendet. Bei meiner Konvertierung verwende ich Reflexion .:
Type type = this.myObject.GetType();
if (type.Name == "MyObjectClass") {
var Voucherrequest = (MyObjectClass)Convert.ChangeType(myObject, typeof(MyObjectClass));
Dies alles setzt voraus, dass Sie wissen, in welchen Typ Sie konvertieren möchten. Sie können sogar einen Wechsel vornehmen und mehrere Typen haben, die Sie auch reflektieren möchten.
Ich bin nicht sicher, ob es funktioniert, aber probieren Sie es aus:
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);
}