Fil*_*erg 26
你可以使用反射.
您的方案可能看起来像这样:
static void Main(string[] args)
{
var list = new List<Mammal>();
list.Add(new Person { Name = "Filip", DOB = DateTime.Now });
list.Add(new Person { Name = "Peter", DOB = DateTime.Now });
list.Add(new Person { Name = "Goran", DOB = DateTime.Now });
list.Add(new Person { Name = "Markus", DOB = DateTime.Now });
list.Add(new Dog { Name = "Sparky", Breed = "Unknown" });
list.Add(new Dog { Name = "Little Kid", Breed = "Unknown" });
list.Add(new Dog { Name = "Zorro", Breed = "Unknown" });
foreach (var item in list)
Console.WriteLine(item.Speek());
list = ReCalculateDOB(list);
foreach (var item in list)
Console.WriteLine(item.Speek());
}
Run Code Online (Sandbox Code Playgroud)
你想在哪里重新计算所有哺乳动物的生日.以上的实现看起来像这样:
internal interface Mammal
{
string Speek();
}
internal class Person : Mammal
{
public string Name { get; set; }
public DateTime DOB { get; set; }
public string Speek()
{
return "My DOB is: " + DOB.ToString() ;
}
}
internal class Dog : Mammal
{
public string Name { get; set; }
public string Breed { get; set; }
public string Speek()
{
return "Woff!";
}
}
Run Code Online (Sandbox Code Playgroud)
所以基本上你需要做的是使用Relfection,它是一种机制,用于检查类型并获取类型属性以及运行时类似的其他内容.下面是一个关于如何为每个获得DOB的哺乳动物的上述DOB添加10天的示例.
static List<Mammal> ReCalculateDOB(List<Mammal> list)
{
foreach (var item in list)
{
var properties = item.GetType().GetProperties();
foreach (var property in properties)
{
if (property.PropertyType == typeof(DateTime))
property.SetValue(item, ((DateTime)property.GetValue(item, null)).AddDays(10), null);
}
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
请记住,使用反射可能很慢,而且通常很慢.
但是,上面会打印出这个:
My DOB is: 2010-03-22 09:18:12
My DOB is: 2010-03-22 09:18:12
My DOB is: 2010-03-22 09:18:12
My DOB is: 2010-03-22 09:18:12
Woff!
Woff!
Woff!
My DOB is: 2010-04-01 09:18:12
My DOB is: 2010-04-01 09:18:12
My DOB is: 2010-04-01 09:18:12
My DOB is: 2010-04-01 09:18:12
Woff!
Woff!
Woff!
Run Code Online (Sandbox Code Playgroud)
Axa*_*dax 12
它被称为反射.
var t = this;
var props = t.GetType().GetProperties();
foreach (var prop in props)
{
if (prop.PropertyType == typeof(DateTime))
{
//do stuff like prop.SetValue(t, DateTime.Now, null);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23786 次 |
| 最近记录: |