例如,我有一个类的静态列表:
public static List<MadjType> MAASource = new List<MadjType>
{
new MadjType{Id = 1, Name = "MAA - 1"},
new MadjType{Id = 2, Name = "MAA - 2"},
new MadjType{Id =3, Name = "MAA - 3"},
new MadjType{Id = 4, Name = "MAA - 4"},
new MadjType{Id = 5, Name = "MAA - 5"},
new MadjType{Id = 6, Name = "MAA - 6"},
new MadjType{Id = 7, Name = "MAA - 7"},
new MadjType{Id = 8, Name = "MAA - 8"},
new MadjType{Id = 9, Name="MAA - 9"},
new MadjType{Id = 10, Name= "MAA - 10"},
};
我有一个资源文件告诉我是否正在为Version1或Version2构建(我将此作为解决方案其他部分的条件,例如
if (ConfigurationResource.Version == "Version2")
{
//return different values
}
)。
所以,对于Version2,我不想在这个静态列表中添加最后几个项目,所以意思是:
new MadjType{Id = 8, Name = "MAA - 8"},
new MadjType{Id = 9, Name="MAA - 9"},
new MadjType{Id = 10, Name= "MAA - 10"},
当我使用资源文件中声明的Version2时,不应包含在MAASource中。
我有什么方法可以为这个静态列表执行此操作?
答案 0 :(得分:2)
这取决于您是否可以静态访问ConfigurationResource.Version
。如果是这样,您可以使用静态构造函数初始化MAASource
。
public static List<MadjType> MAASource { get; set; }
static MyClass(){
if (ConfigurationResource.Version == "Version1")
{
//return values for Version1
}
if (ConfigurationResource.Version == "Version2")
{
//return values for Version2
}
}
答案 1 :(得分:1)
您可以在静态构造函数中初始化值。但这需要版本在静态上下文中也可用。
public static List<MadjType> MAASource { get; private set; }
static MyClass()
{
switch (ConfigurationResource.Version)
{
case "Version1":
MAASource = new List<MadjType>
{
new MadjType { Id = 1, Name = "MAA - 1" },
new MadjType { Id = 2, Name = "MAA - 2" },
new MadjType { Id = 3, Name = "MAA - 3" },
new MadjType { Id = 4, Name = "MAA - 4" },
new MadjType { Id = 5, Name = "MAA - 5" },
new MadjType { Id = 6, Name = "MAA - 6" },
new MadjType { Id = 7, Name = "MAA - 7" },
new MadjType { Id = 8, Name = "MAA - 8" },
new MadjType { Id = 9, Name = "MAA - 9" },
new MadjType { Id = 10, Name = "MAA - 10" },
};
break;
case "Version2":
MAASource = new List<MadjType>
{
new MadjType { Id = 1, Name = "MAA - 1" },
new MadjType { Id = 2, Name = "MAA - 2" },
new MadjType { Id = 3, Name = "MAA - 3" },
new MadjType { Id = 4, Name = "MAA - 4" },
new MadjType { Id = 5, Name = "MAA - 5" },
new MadjType { Id = 6, Name = "MAA - 6" },
new MadjType { Id = 7, Name = "MAA - 7" },
};
break;
}
}
您可以创建列表并根据版本添加项目,而不是在案例陈述中定义整个集合。