获得“基本”数据类型,而不是奇怪的可为空的数据类型,通过 C# 中的反射
我的基本需求是从 LINQ to SQL 查询生成的匿名类型中获取数据类型。
我有一段代码(比我能写的更聪明,因为我还没有真正深入研究反射),它从匿名类型返回数据类型,并且非常适合 linq2sql 属性中标记为“不可为空”的元素。因此,如果我有一个字符串,它将作为 System.String 返回。但是,当元素可为空时,我最终得到它的“全名”:
{Name = "Nullable1" FullName = "System.Nullable
1[[System.Decimal, mscorlib, Version =4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}
在这种情况下,我想要提取的是 System.Decimal 类型(在字符串或其他情况下,我只想要 System.String)。我查看了所有属性,但找不到任何似乎可以存储此内容的内容。
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);
}
LINQ 查询(我认为这里并不重要):
var theData = from r in db.tblTestEdits select new { myitem = r.textField, mydecimal = r.decimalField };
我发现这个链接似乎试图解决类似的问题。
http://ysgitdiary.blogspot.com/2010/02/blog-post.html
虽然它似乎返回类型的“字符串”而不是实际类型,但这正是我需要的。不知道如何转换这样的东西。
非常感谢大家。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可能想要这样的东西
You want something like this maybe