[英]In Reflection, how to set a correct value for a property?
我的目標是找到所有的“字符串”類型屬性,並將它們分配給特定的字符串值,例如“這是測試字符串”。
我現在可以在一個類中找到所有的字符串類型屬性,但是在將字符串值分配給一個類中的屬性(另一個類的類屬性)時總是會遇到問題。
public class Credit_Card
{
public string brand { get; set; }
public int billing_phone { get; set; }
public string credit_card_verification_number { get; set; }
public Expiration expiration { get; set; }
}
public class Expiration
{
public string month { get; set; }
public string year { get; set; }
}
class Program
{
static void Main(string[] args)
{
Credit_Card credcard = new Credit_Card { brand = "Visa", billing_phone = 12345, credit_card_verification_number = "1234", expiration = new Expiration { month = "11", year = "2016" } };
foreach (PropertyInfo prop in GetStringProperties(credcard.GetType()))
{
prop.SetValue(credcard,"testing string!!",null);
Console.WriteLine(prop.GetValue(credcard,null));
}
Console.ReadLine();
}
public static IEnumerable<PropertyInfo> GetStringProperties(Type type)
{
return GetStringProperties(type, new HashSet<Type>());
}
public static IEnumerable<PropertyInfo> GetStringProperties(Type type, HashSet<Type> alreadySeen)
{
foreach (var prop in type.GetProperties())
{
var propType = prop.PropertyType;
if (propType == typeof(string))
yield return prop;
else if (alreadySeen.Add(propType))
foreach (var indirectProp in GetStringProperties(propType, alreadySeen))
yield return indirectProp;
}
}
}
當循環運行到Expiration類的“ month”屬性時,它將始終引發異常。
如何將正確的值分配給正確的實例?
如果要分配month
和year
值,則需要通過執行Type.GetType(CredCard.Expiration).Properties
.Properties來獲取其PropInfo,因為它們不是credcard
的屬性, credcard.Expiration
屬性。
您將必須檢查屬性並將它們分配給credcard.Expiration
而不是credcard
。
// prop.Name == "month" || prop.Name == "year"
prop.SetValue(credcard.Expiration, "somestring");
另一種選擇是將新的Expiration對象分配給Expiration屬性:
if(prop.Name.Equals("Expiration"))
{
var expiration = new Expiration
{
month = "someString",
year = "someString"
};
prop.SetValue(credcard,expiration);
}
查看代碼,您將獲取Credit_Card
上的所有字符串屬性,然后以遞歸方式獲取子對象上的所有字符串屬性。
您的問題來自於它從Expiration
返回string month
的事實。 然后,您嘗試在Credit_Card
實例credcard
上設置Expiration.month
屬性。
那行不通。 目標必須匹配聲明PropertyInfo
的相同Type
。 這就是為什么您得到:
未處理System.Reflection.TargetException,消息為“對象與目標類型不匹配”
您需要拆分循環,以便按正確的層次結構鏈進行操作,並具有將隨數據更新的正確實例(目標)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.