飛我想對一個對象轉換爲在運行時被分配一個類型。轉換爲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);
}
你可以舉一個例子,這將用於?如果你不知道具體類型爲什麼你需要投它?你有沒有想過要充滿活力? – Carsten
當你將參數傳遞給'Foo'方法時,你知道類型是什麼嗎? –
@JamesJohnson我認爲你總是可以知道你是否需要:-) – username