Gli*_*kot 2 c# reflection types anonymous-types
我的基本需求是从LINQ to SQL查询生成的匿名类型中获取数据类型.
我有一段代码(比我能写的更聪明,因为我还没有深入研究过反射)从匿名类型中返回数据类型,并且对于linq2sql属性中标记为'not nullable'的元素非常有效.所以,如果我有一个字符串,它将作为System.String返回.但是,当元素可以为空时,我最终会得到它的"全名":
{Name ="Nullable 1" FullName = "System.Nullable1 [[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);
}
Run Code Online (Sandbox Code Playgroud)
LINQ查询(我认为这不重要):
var theData = from r in db.tblTestEdits select new { myitem = r.textField, mydecimal = r.decimalField };
Run Code Online (Sandbox Code Playgroud)
我发现这个链接似乎试图解决类似的问题.
http://ysgitdiary.blogspot.com/2010/02/blog-post.html
虽然它似乎返回类型的"字符串"而不是实际类型,这是我需要的.不知道如何转换这样的东西.
非常感谢大家.
private static Type GetCoreType(Type type)
{
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>))
return Nullable.GetUnderlyingType(type);
else
return type;
}
Run Code Online (Sandbox Code Playgroud)