获取通用对象的类名

时间:2014-02-07 21:23:51

标签: c# .net generics

我有一个程序,它将电子表格作为输入,如果有任何错误,则将错误转储回单独的电子表格,原始数据由用户输入并显示错误消息。

要保存错误记录及其错误消息,我有一个Dictionary对象,可能包含两种类型的对象之一作为键。它将具有DataRow对象或名称为ZipCodeTerritory的实体框架模型对象。

由于我可能有数据输入错误(即111/2/1980作为日期),我需要创建一个单独的错误类,用于填充电子表格,我需要转换DataRow / { {1}}键进入此特殊错误类。但是..在我这样做之前,我需要确定我正在使用哪种类型。我在下面使用的方法无法使用ZipCodeTerritoryDataRow对象。任何人都知道更好的方法来确定通用对象的类型?

C#

ZipCodeTerritory

ZipCodeError

//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();
    }

2 个答案:

答案 0 :(得分:3)

使用is关键字

if ( item.Key is DataRow )
{
    zip = new ZipCodeError((DataRow)item.Key);
}
else if ( item.Key is ZipCodeTerritory )
{
    zip = new ZipCodeError((ZipCodeTerritory)item.Key);
}
else
{
    ...
}

答案 1 :(得分:2)

您的实施中还有额外的GetType()。当您在RuntimeType上致电Type

时,您将获得GetType,这是Type
//Determine type and separate key and value
Type type = item.Key.GetType();
if (type.Name.Equals("DataRow"))
{
    zip = new ZipCodeError((DataRow)item.Key);
}
else if (type.Name.Equals("ZipCodeTerritory"))
{
    zip = new ZipCodeError((ZipCodeTerritory)item.Key);
}
else
{
    ...
}