lundi 13 avril 2015

In Reflection, how to set a correct value for a property?

My target is to find all the "string" type properties, and assign them to a specific string value, like "This is a testing string".


I can find all the string type properties in a class now, but always have problems when assigning string value to the property in a class, which is the class property of another class.



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


It always throws the exception when the loop runs to "month" property of Expiration class.


How can I assign the correct value into the correct instance?






Aucun commentaire:

Enregistrer un commentaire