How to get underlying type from typed DataSet
I've been searching a lot but I haven't found anything about this question. I'm making a log of my app and I'm printing types of variables and their values. I want to do the same for every object I receive as parameter, and for every object I return too. So I'm returning a typed dataset (MyDataSet that's defined as MyDataSetType e.g.) but I can't retrieve MyDataSetType name.
I have a method that given a dataset, returns a string with all the content. Something like this:
string GetLogStringFromDataSetParameter(System.Data.DataSet incomingDataSet)
{
StringBuilder strReturn = new StringBuilder();
strReturn.Append("DataSet (type ");
strReturn.Append(GetTypeName(incomingDataSet));
strReturn.Append("). ");
// .. do some validations
strReturn.Append("Contain开发者_如何学Gos ");
strReturn.Append(incomingDataSet.Tables.Count);
strReturn.Append(" tables.");
for (int i = 0; i < incomingDataSet.Tables.Count; i++)
{
System.Data.DataTable table = incomingDataSet.Tables[i];
strReturn.Append(" Tabla " + table.TableName + " (" + i + ") ");
strReturn.Append(<Method to list table content>);
}//yes, this could have been a foreach loop...
return FormatStringToLog(strReturn);
} //end
As you can see, I'm using my own method GetTypeName to retrieve de name of my typed dataset. I've made this method after some investigation through this site:
public static string GetTypeName<T>(T parameter)
{
string strReturn = typeof(T).Name;
if (strReturn.IndexOf("Nullable") >= 0)
strReturn = Nullable.GetUnderlyingType(typeof(T)).Name;
else if (strReturn.IndexOf("List") >= 0)
{
strReturn = "List of " + typeof(T).GetGenericArguments()[0].Name;
if (strReturn.IndexOf("Nullable") >= 0)
strReturn = "List of " + Nullable.GetUnderlyingType(typeof(T).GetGenericArguments()[0]).Name;
}
return strReturn;
}
When I'm inside of GetLogStringFromDataSetParameter
method, if I try typeof(MyDataSet)
it returns correctly MyDataSetType
. But when I make the call to GetTypeName
it returns DataSet
only, the generic type. Why is this? Is there any way to retrieve correctly MyDataSetType
without calling directly to typeof()
?
I hope I've explained everything clear enough. Thanks in advance.
That is because typeof(T)
has nothing to do with the incoming Dataset type.
At compile-time the method is instantiated for the plain Datset type, and T is of type Dataset.
To solve it, simply use parameter.GetType()
instead of typeof(T)
精彩评论