簡體   English   中英

使用Convert.ChangeType強制轉換為屬性的類型

[英]Casting To A Property's Type Using Convert.ChangeType

我需要遍歷對象的屬性並獲取每個原始屬性(和字符串)的值。 我已經有適當的代碼來處理索引器,復雜的對象和可為空的基元,因此不必擔心這些(為了簡化起見,我從代碼中排除了它們)。 我遇到的問題是當我使用Convert.ChangeType()時。 變量“值”始終為System.Object類型。 如何將其轉換為“ SomeObject”對象中所示的字符串或整數?

SomeObject someObject = new SomeObject();

foreach (PropertyInfo propertyInfo in someObject.GetType().GetProperties())
{
    Type propertyType = propertyInfo.PropertyType;

    // How can I cast this to the type of "propertyType"?
    var value = Convert.ChangeType(propertyInfo.GetValue(someObject, null), propertyType);
}

public class SomeObject
{
    public string SomeString { get; set; }
    public int SomeInt { get; set; }
}

你可以做類似的事情

if (propertyType == typeof(int))
{
    var value = (int)Convert.ChangeType(propertyInfo.GetValue(testo, null), propertyType);
}
else if(propertyType == typeof(string))
{
    var value = (string)Convert.ChangeType(propertyInfo.GetValue(testo, null), propertyType);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM