我正在通过创建几十个自定义类型的静态对象来设置测试数据。我希望有一个这些对象的列表,以便我可以在测试期间进行动态断言。这是类和对象:
public class Publication
{
public string Name { get; set; }
public string DropdownText { get; set; }
public string DropdownValue { get; set; }
public string BaseURL { get; set; }
public static Publication MotocrossWeekly = new Publication {
Name = "Motocross Weekly",
DropdownText = "Motocross Weekly",
DropdownValue = "18",
};
public static Publication ExtremeWelding = new Publication {
Name = "Extreme Welding",
DropdownText = "Extreme Welding",
DropdownValue = "6",
};
public static Publication HackersGuide = new Publication {
Name = "Hacker's Guide to Security",
DropdownText = "Hacker's Guide",
DropdownValue = "36",
};
...
public static IList<Publication> Publications = ???;
目标是拥有一个静态的Publications列表,其中包含Publication类中的所有Publication对象。这是为了避免在每次添加或从系统中删除时,必须手动写出列表中的每个对象并编辑列表。
我认为这可以用反思来完成,但我找不到我想要做的具体细节。
答案 0 :(得分:1)
嗯,要获取公共,静态字段列表,您可以这样做:
typeof(Publication).GetFields(BindingFlags.Static|BindingFlags.Public)
并循环或使用Linq查找类型为Publication
的那些。
但您的班级设计还需要考虑其他一些事项:
HackersGuide
对象替换Publication
。更好的设计是获得只有静态属性:
private static Publication _MotocrossWeekly = new Publication {
Name = "Motocross Weekly",
DropdownText = "Motocross Weekly",
DropdownValue = "18",
};
public static MotocrossWeekly {get {return _MotocrossWeekly; } }
// etc.
答案 1 :(得分:0)
这样的事情应该有效:
FieldInfo[] fields = typeof(Publication).GetFields(BindingFlags.Public | BindingFlags.Static)
FieldInfo
应告诉您有关该领域的所有信息:
https://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo(v=vs.110).aspx
答案 2 :(得分:0)
你可以使用反射来做到这一点
public class Publication
{
public string Name { get; set; }
public string DropdownText { get; set; }
public string DropdownValue { get; set; }
public string BaseURL { get; set; }
public static Publication MotocrossWeekly = new Publication
{
Name = "Motocross Weekly",
DropdownText = "Motocross Weekly",
DropdownValue = "18",
};
public static Publication ExtremeWelding = new Publication
{
Name = "Extreme Welding",
DropdownText = "Extreme Welding",
DropdownValue = "6",
};
public static Publication HackersGuide = new Publication
{
Name = "Hacker's Guide to Security",
DropdownText = "Hacker's Guide",
DropdownValue = "36",
};
public static IList<Publication> Publications
{
get
{
return typeof(Publication).GetFields(BindingFlags.Static | BindingFlags.Public)
.Select(f => (Publication)f.GetValue(null))
.ToList();
}
}
}