获得“基本”数据类型,而不是怪异可空一体,通过反射在C# [英] Getting 'basic' datatype rather than weird nullable one, via reflection in c#
问题描述
我的基本需要是从一个LINQ生成的SQL查询匿名类型得到的数据类型。
我有一段代码(聪明,比我可以写,因为我还没有真正钻研反射)从一个匿名类型返回的数据类型,并完全适用于标注在LINQ2SQL特性不能为空的元素。所以,如果我有一个字符串将返回为System.String。然而,当元素为空我结束了它的全名是:
{NAME =可空 1全名= System.Nullable
1 [System.Decimal,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089]]}
我要的提取是在这样的情况下,System.Decimal类型(在字符串或什么的情况下,我只是想System.String)。我已经通过属性看,找不到任何东西,似乎存储此
私有静态字典<字符串类型> ; GetFieldsForType< T>(IEnumerable的< T>数据)
{
对象o = data.First();
变种属性= o.GetType()的GetProperties();
返回properties.ToDictionary(财产= GT; property.Name,财产= GT; property.PropertyType);
}
LINQ查询(我不认为真正的问题在这里):
VAR海图=从R IN db.tblTestEdits选择新{myitem = r.textField,mydecimal = r.decimalField};
我发现这个链接,似乎试图解决类似的事情。结果
http://ysgitdiary.blogspot.com/2010/02/blog-post.html
虽然它似乎返回的类型是什么,而不是实际的类型,这正是我需要的弦。不知道如何转换这样的事情。
非常感谢所有。
私有静态类型GetCoreType(类型类型)
{
如果(type.IsGenericType&安培;&安培;
type.GetGenericTypeDefinition()== typeof运算(可空<>))
返回Nullable.GetUnderlyingType(类型);
,否则
返回类型;
}
My basic need is to get the datatypes from an anonymous type generated from a LINQ to SQL query.
I have a piece of code (cleverer than I could write, since I haven't really delved into reflection) which returns the datatypes from an anonymous types, and works perfectly for the elements marked 'not nullable' in the linq2sql properties. So, if I have a string it will return as System.String. However, when the element is nullable I end up with the 'full name' of it being:
{Name = "Nullable1" FullName = "System.Nullable
1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}
All I want to extract is the System.Decimal type in such a case (and in cases of strings or whatever, I'd just want System.String). I've looked through the properties and can't find anything that seems to store this.
private static Dictionary<string, Type> GetFieldsForType<T>(IEnumerable<T> data)
{
object o = data.First();
var properties = o.GetType().GetProperties();
return properties.ToDictionary(property => property.Name, property => property.PropertyType);
}
The LINQ query (which I don't think really matters here):
var theData = from r in db.tblTestEdits select new { myitem = r.textField, mydecimal = r.decimalField };
I found this link that seems to try to address a similar thing.
http://ysgitdiary.blogspot.com/2010/02/blog-post.html
Though it seems to return a "string" of what the type is rather than the actual type, which is what I need. Not sure how to convert such a thing.
Many thanks all.
private static Type GetCoreType(Type type)
{
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>))
return Nullable.GetUnderlyingType(type);
else
return type;
}
这篇关于获得“基本”数据类型,而不是怪异可空一体,通过反射在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!