我正致力于代码生成,并遇到了泛型问题.这是导致我问题的"简化"版本.
Dictionary<string, DateTime> dictionary = new Dictionary<string, DateTime>();
string text = dictionary.GetType().FullName;
Run Code Online (Sandbox Code Playgroud)
使用上面的代码片段,其值text如下:
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.DateTime, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Run Code Online (Sandbox Code Playgroud)
(添加了换行符以提高可读性.)
有没有办法type在不解析上面的字符串的情况下以不同的格式获取类型name()?我希望得到以下结果text:
System.Collections.Generic.Dictionary<System.String, System.DateTime>
Run Code Online (Sandbox Code Playgroud) 我的基本需求是从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
虽然它似乎返回类型的"字符串"而不是实际类型,这是我需要的.不知道如何转换这样的东西.
非常感谢大家.