C# 获得';基本';数据类型,而不是奇怪的可空类型,通过c中的反射#

C# 获得';基本';数据类型,而不是奇怪的可空类型,通过c中的反射#,c#,reflection,types,anonymous-types,C#,Reflection,Types,Anonymous Types,我的基本需求是从LINQ到SQL查询生成的匿名类型中获取数据类型 我有一段代码(比我能写的更聪明,因为我没有真正深入研究反射),它从匿名类型返回数据类型,并且非常适用于linq2sql属性中标记为“not nullable”的元素。因此,如果我有一个字符串,它将返回System.string。但是,当该元素可为空时,我最终将其“全名”设置为: {Name=“Nullable1”FullName=“System.Nullable1[[System.Decimal,mscorlib,Version=

我的基本需求是从LINQ到SQL查询生成的匿名类型中获取数据类型

我有一段代码(比我能写的更聪明,因为我没有真正深入研究反射),它从匿名类型返回数据类型,并且非常适用于linq2sql属性中标记为“not nullable”的元素。因此,如果我有一个字符串,它将返回System.string。但是,当该元素可为空时,我最终将其“全名”设置为:

{Name=“Nullable
1”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);
    }
我发现这个链接似乎试图解决类似的问题。

虽然它似乎返回类型的“字符串”,而不是实际的类型,这正是我所需要的。不知道如何转换这样的东西

非常感谢大家。

私有静态类型GetCoreType(类型类型)
private static Type GetCoreType(Type type)
{
    if (type.IsGenericType &&
        type.GetGenericTypeDefinition() == typeof(Nullable<>))
        return Nullable.GetUnderlyingType(type);
    else
        return type;
}
{ 如果(type.IsGenericType&& type.GetGenericTypeDefinition()==typeof(可为null)) 返回Nullable.GetUnderlineType(类型); 其他的 返回类型; }
也许你想要这样的东西

        Type targetType;
        bool isNullable;

        // Do we have a nullable type?
        if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            isNullable = true;
            targetType = type.GetGenericArguments()[0];
        }
        else
        {
            isNullable = false;
            targetType = type;
        }
类型targetType;
布尔值为空;
//我们有可为空的类型吗?
if(type.IsGenericType&&type.GetGenericTypeDefinition().Equals(typeof(null)))
{
isNullable=true;
targetType=type.GetGenericArguments()[0];
}
其他的
{
isNullable=false;
targetType=类型;
}

太棒了!非常感谢mquander!有趣的是,当我在property inspector中查看“底层”属性时,它们仍然是这些巨大的文本块。非常感谢。调试器的对象检查器通常需要将所有内容都转换为文本才能显示给您,而它知道如何将通用的可为空类型表示为文本的最佳方式就是那一大堆废话。嗨,詹姆斯,我想我应该从第一个答案开始,然后继续工作,下面的一个很好地完成了这一任务。不过我也会保留这个片段,谢谢你的帮助!
        Type targetType;
        bool isNullable;

        // Do we have a nullable type?
        if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            isNullable = true;
            targetType = type.GetGenericArguments()[0];
        }
        else
        {
            isNullable = false;
            targetType = type;
        }