360 Stimmen

Einstellung einer Eigenschaft durch Reflexion mit einem String-Wert

Ich möchte eine Eigenschaft eines Objekts über Reflection mit einem Wert des Typs string . Angenommen, ich habe zum Beispiel eine Ship Klasse, mit einer Eigenschaft von Latitude die ein double .

Ich würde gerne Folgendes tun:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null);

So wie es ist, führt dies zu einem ArgumentException :

Objekt vom Typ 'System.String' kann nicht in den Typ 'System.Double' konvertiert werden.

Wie kann ich einen Wert in den richtigen Typ konvertieren, basierend auf propertyInfo ?

8voto

John Calsbeek Punkte 35029

Sie suchen wahrscheinlich nach dem Convert.ChangeType Methode. Zum Beispiel:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

5voto

tvanfosson Punkte 506878

Verwendung von Convert.ChangeType und den zu konvertierenden Typ aus der Datei PropertyInfo.PropertyType .

propertyInfo.SetValue( ship,
                       Convert.ChangeType( value, propertyInfo.PropertyType ),
                       null );

5voto

Ali Karaca Punkte 2605

Ich werde diese Frage mit einer allgemeinen Antwort beantworten. In der Regel funktionieren diese Antworten nicht mit Leitfäden. Hier ist eine funktionierende Version auch mit Hilfslinien.

var stringVal="6e3ba183-89d9-e611-80c2-00155dcfb231"; // guid value as string to set
var prop = obj.GetType().GetProperty("FooGuidProperty"); // property to be setted
var propType = prop.PropertyType;

// var will be type of guid here
var valWithRealType = TypeDescriptor.GetConverter(propType).ConvertFrom(stringVal);

3voto

bytebender Punkte 7216

Oder Sie könnten es versuchen:

propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

//But this will cause problems if your string value IsNullOrEmplty...

2voto

Serhiy Punkte 333

Wenn Sie eine Metro-App schreiben, sollten Sie anderen Code verwenden:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType));

Anmerkung:

ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");

anstelle von

ship.GetType().GetProperty("Latitude");

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X