我有一個程序,它以電子表格作爲輸入,並且如果有任何錯誤,則將錯誤轉儲回單獨的電子表格,原始數據由用戶輸入並顯示錯誤消息。獲取通用對象的類名稱
要保存錯誤的記錄及其錯誤消息,我有一個Dictionary
對象,其中可能包含兩種類型的對象之一作爲關鍵字。它將擁有一個DataRow
對象或一個名稱爲ZipCodeTerritory
的實體框架模型對象。
因爲我有可能數據輸入錯誤(即111/2/1980爲日期),我需要創建我用來填充電子表格中的單獨的錯誤類,我需要到DataRow
/ZipCodeTerritory
鍵轉換成這特殊錯誤類。但是,在我這樣做之前,我需要確定我正在使用哪種類型。我在下面使用的方法無法使用,或者使用DataRow
或ZipCodeTerritory
對象。任何人都知道更好的方法來確定一個通用對象的類型?
C#
//Definition of the Dictionary I'm using to hold the errored records/messages
private static Dictionary<object, string> _errors = new Dictionary<object, string>();
//Snippet of code to show how I'm adding one of the ZipCodeTerritory objects
//"record" object is of type ZipCodeTerritory
if (string.IsNullOrEmpty(record.LastUpdateId))
{
//Add to error list
_issues++;
_errors.Add(record, "Missing last update Id");
continue;
}
//Section of code that tries to separate key/value and determine type
foreach (KeyValuePair<object, string> item in errors)
{
//Use custom class in case of data errors
//resulting from bad input on spreadsheet
ZipCodeError zip;
//Determine type and separate key and value
Type type = item.Key.GetType();
if (type.GetType().Name.Equals("DataRow"))
{
zip = new ZipCodeError((DataRow)item.Key);
}
else if (type.GetType().Name.Equals("ZipCodeTerritory"))
{
zip = new ZipCodeError((ZipCodeTerritory)item.Key);
}
else
{
//Code always falls through to this....
zip = new ZipCodeError();
}
ZipCodeError
public class ZipCodeError
{
//Create generic object properties just in case of
//typos or any other unforseen input errors from the spreadsheet
public object ChannelCode { get; set; }
public object DrmTerrDesc { get; set; }
public object IndDistrnId { get; set; }
public object StateCode { get; set; }
public object ZipCode { get; set; }
public object EndDate { get; set; }
public object EffectiveDate { get; set; }
public object LastUpdateId { get; set; }
public object LastUpdateDate { get; set; }
public object ErrorCodes { get; set; }
public object Status { get; set; }
public object Id { get; set; }
public ZipCodeError(){}
public ZipCodeError(DataRow row)
{
this.ChannelCode = row[0];
this.DrmTerrDesc = row[1];
this.IndDistrnId = row[2];
this.StateCode = row[3];
this.ZipCode = row[4];
this.EndDate = row[5];
this.EffectiveDate = row[6];
this.LastUpdateId = row[7];
this.ErrorCodes = row[8];
this.Status = row[9];
this.Id = row[10];
}
public ZipCodeError(ZipCodeTerritory master)
{
this.ChannelCode = master.ChannelCode;
this.DrmTerrDesc = master.DrmTerrDesc;
this.IndDistrnId = master.IndDistrnId;
this.StateCode = master.StateCode;
this.ZipCode = master.ZipCode;
this.EndDate = master.EndDate;
this.EffectiveDate = master.EffectiveDate;
this.LastUpdateDate = master.LastUpdateDate;
this.LastUpdateId = master.LastUpdateId;
this.ErrorCodes = master.ErrorCodes;
this.Status = master.Status;
this.Id = master.Id;
}
}
什麼叫
GetType
你'type.GetType()。Name'然後返回? – i3arnon爲什麼不使用''的字典?關於你在做什麼還有其他一些問題,但那個問題真的很突出。不過,真的,如果你有兩種類型的數據,我看不出有什麼理由讓它們保持在同一個集合中。一定會有更好的辦法。 –
Magus