【发布时间】:2015-04-13 23:04:08
【问题描述】:
我的目标是找到所有“字符串”类型的属性,并将它们分配给特定的字符串值,例如“这是一个测试字符串”。
我现在可以在一个类中找到所有字符串类型的属性,但是在为一个类中的属性赋值时总是出现问题,这是另一个类的类属性。
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 类的“月”属性时,它总是抛出异常。
如何将正确的值分配给正确的实例?
【问题讨论】:
-
你遇到了什么异常?
-
System.Reflection.TargetException 未处理,消息为“对象与目标类型不匹配”。它发生在 prop.SetValue(credcard,"testing string!!",null)
标签: c# reflection properties