2011-09-30 41 views
14

飛我想對一個對象轉換爲在運行時被分配一個類型。轉換爲A類在C#.NET

例如,假設我有一個函數將字符串值(從TextBox or Dropdownlist)分配給Object.Property

我怎麼會值轉換爲正確的類型?例如,它可能是一個整數,字符串或枚舉。

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); 
} 
+0

你可以舉一個例子,這將用於?如果你不知道具體類型爲什麼你需要投它?你有沒有想過要充滿活力? – Carsten

+0

當你將參數傳遞給'Foo'方法時,你知道類型是什麼嗎? –

+0

@JamesJohnson我認爲你總是可以知道你是否需要:-) – username

回答

28

您需要使用Convert.ChangeType(...)功能(輸入可以很容易地將一個對象......我只是一個字符串版本預烘):

/// <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); 
} 
+0

這種方法唯一的缺點是它不適用於可空類型。 –

+0

只是注意到,你確實有一些可爲空類型的邏輯。 –

+0

Convert.ChangeType()是令人滿意的,雖然我應該對枚舉進行一些檢查,tnx fordareh。 – nAviD

2

通用型轉換器是你所尋求的!不是一個容易的事..

試試這個辦法:

Universal Type Converter

你可以在的NuGet Install-Package UniversalTypeConverter

而且,使用Generics在這裏的問題?如果您至少知道轉換的目標類型,它將有助於解決方案。

0

我不敢肯定它的工作原理,但不妨一試:

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); 
} 
+0

它不起作用,因爲To ()中的泛型類型t必須在編譯時定義。 – nAviD

+0

@Navid:不,因爲我在回答開始時提到的擴展方法。我很確定它將在運行時進行評估... – Marco

+0

我可以說這是行不通的,而@Navid是正確的。通用方法需要在編譯時提供類型 – workabyte

1

這裏的另一種方式,你可以做到這一點,但我不知道

沒有對泛型類型的支持:

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); 
} 

隨着對泛型類型的支持:

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); 
} 
0

我用C#轉換功能。我正在做我的轉換的方式是使用反射。:

Type type = this.myObject.GetType(); 

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

這是假設你知道你想要轉換成什麼類型​​。你甚至可以做一個開關,並有多種你想反映的類型。