Моя цель — найти все свойства типа «строка» и присвоить их определенному строковому значению, например «Это тестовая строка».
Теперь я могу найти все свойства строкового типа в классе, но всегда возникают проблемы при присвоении строкового значения свойству в классе, которое является свойством класса другого класса.
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.
Как я могу присвоить правильное значение правильному экземпляру?