以下是从DB获取所需数据并使用类初始化程序初始化属性成员的代码片段:
var list =
(from spcdata_tb in _dbContext.SPCDATA_TB
from wh_master_tb in _dbContext.WH_MASTER_TB
where spcdata_tb.FACTORY_CODE == factoryCode
&& spcdata_tb.LINE_CODE == lineCode
&& spcdata_tb.MODEL_NO == modelNumber
&& spcdata_tb.FACTORY_CODE == wh_master_tb.WH_CODE
&& spcdata_tb.LINE_CODE == wh_master_tb.LINE_CODE
select new SPCMeasureData()
{
operDateString = spcdata_tb.DATA_WDATE,
operTimeString = spcdata_tb.DATA_WTIME,
inputTimeString = spcdata_tb.DATA_ITIME,
modelNumString = spcdata_tb.MODEL_NO,
DataList[0] = spcdata_tb.DATA1,
DataList[1] = spcdata_tb.DATA2,
DataList[2] = spcdata-tb.DATA3
});
然而,它抛出了无法找到DataList [0]和DataList [1]的编译器错误。
public class SPCMeasureData
{
public DateTime operDateString { get; set; }
public TimeSpan? operTimeString { get; set; }
public TimeSpan? inputTimeString { get; set; }
public string modelNumString { get; set; }
public string modelNameString { get; set; }
public string lotNumString { get; set; }
public int dataSeqString { get; set; }
public string factoryCodeString { get; set; }
public string factoryNameString { get; set; }
public string lineCodeString { get; set; }
public string lineNameString { get; set; }
public string cusNameString { get; set; }
public string equipNumString { get; set; }
public float?[] dataList = new float?[30];
public float?[] DataList
{
get { return dataList; }
set { dataList = value; }
}
}
我怀疑虽然可以从类初始化程序初始化DataList的实际数组成员,但是不能以相同的方式分配其数组成员。
有没有办法克服这个问题?
答案 0 :(得分:1)
对象初始值设定项语法只能识别对象的直接成员。因此,在这种情况下,它可以识别数组属性DataList
,但不能识别DataList[index]
。解决方法是使用数组初始化器语法。当你有一个复杂的属性,一个属于另一个类的属性时,会发生类似的事情。在这种情况下,请使用其他对象初始化程序语法。例如:
public class OtherClass
{
public string Prop1 { get; set; }
}
public class MainClass
{
public OtherClass ComplexProperty { get; set; }
public float?[] ArrayFloatProperty { get; set; }
public List<string> CollectionProperty { get; set; }
}
MainObject
可以通过以下方式初始化:
var mainObj = new MainClass
{
ArrayFloatProperty = new float? [] {0f, 2f, 3f},
ComplexProperty = new OtherClass { Prop1 = "string property" },
CollectionProperty = new List<string> { "str1", "str2", "str3" }
};