基於http://alexreg.wordpress.com/2009/05/03/strongly-typed-csv-reader-in-c/,我創建了一個可以讀取不同文件類型的DLL。我也有成功運行的單元測試。我創建一個結構體並將其用作泛型類型。c#結構字段是「從不分配給」警告
無論如何,當我編譯時,我得到每個結構字段的警告。例如:字段'FileReader.Tests.CsvReader.Record.Field1'永遠不會分配給,並且將始終具有其默認值0
我實際上是用SetValueDirect()設置值,當我運行測試或調試代碼,我可以驗證。那麼爲什麼它給了我那個錯誤,我該如何避免或修復它?
這裏有一些基本的代碼給你一個想法。我猜我沒有提供足夠的,但希望有人有線索。
public abstract class FileReader<TRecord> : IDisposable where TRecord : struct
{
public TRecord? ReadRecord()
{
List<string> fields;
string rawData;
this.recordNumber++;
while (this.ReadRecord(this.fieldTypeInfoList.Length, out fields, out rawData))
{
try
{
// Insert the current record number to the beginning of the field list
fields.Insert(0, this.recordNumber.ToString(CultureInfo.InvariantCulture));
// Convert each field to its correct type and set the value
TRecord record = new TRecord();
FieldTypeInfo fieldTypeInfo;
object fieldValue;
// Loop through each field
for (int i = 0; i < this.fieldTypeInfoList.Length; i++)
{
fieldTypeInfo = this.fieldTypeInfoList[i];
bool allowNull = fieldTypeInfo.AllowNull == null ? this.AllowNull : fieldTypeInfo.AllowNull.Value;
if (i >= fields.Count && !allowNull)
{
// There are no field values for the current field
throw new ParseException("Field is missing", this.RecordNumber, fieldTypeInfo, rawData);
}
else
{
// Trim the field value
bool trimSpaces = fieldTypeInfo.TrimSpaces == null ? this.TrimSpaces : fieldTypeInfo.TrimSpaces.Value;
if (trimSpaces)
{
fields[i] = fields[i].Trim();
}
if (fields[i].Length == 0 && !allowNull)
{
throw new ParseException("Field is null", this.RecordNumber, fieldTypeInfo, rawData);
}
try
{
fieldValue = fieldTypeInfo.TypeConverter.ConvertFromString(fields[i]);
}
catch (Exception ex)
{
throw new ParseException("Could not convert field value", ex, this.RecordNumber, fieldTypeInfo, rawData);
}
fieldTypeInfo.FieldInfo.SetValueDirect(__makeref(record), fieldValue);
}
}
return record;
}
catch (ParseException ex)
{
ParseErrorAction action = (ex.FieldTypeInfo.ParseError == null) ? DefaultParseErrorAction : ex.FieldTypeInfo.ParseError.Value;
switch (action)
{
case ParseErrorAction.SkipRecord:
continue;
case ParseErrorAction.ThrowException:
throw;
case ParseErrorAction.RaiseEvent:
throw new NotImplementedException("Events are not yet available", ex);
default:
throw new NotImplementedException("Unknown ParseErrorAction", ex);
}
}
}
return null;
}
}
它可能是更容易簡化你的榜樣...... – 2009-10-29 16:38:08
我開始這樣做,但隨後似乎過於簡單化,我想最重要的部分是: fieldTypeInfo .FieldInfo.SetValueDirect(__ makeref(record),fieldValue); – 2009-10-29 16:40:55
重點是:沒有簡單的例子,我們可以'再現你所看到的...所以有點難以滿懷信心地回答。 – 2009-10-29 17:09:16