检查type是否为CLR对象

问题描述 投票:2回答:3

我正在尝试序列化一个对象,并想知道XmlReader.ReadElementContentAsObject()ReadElementContentAs()是否可以使用某种类型。

我可以询问一个类型是否是CLR类型,所以我知道我可以将它传递给这些方法吗?

if(myType.IsCLRType) // how can I find this property?
    myValue = _cReader.ReadElementContentAsObject();
c# xmlreader
3个回答
3
投票

我想我正在寻找这个名单:http://msdn.microsoft.com/en-us/library/xa669bew.aspx

你可以用Type.GetTypeCode(type)获得大部分路径,但坦率地说,我希望你最好的选择更简单:

static readonly HashSet<Type> supportedTypes = new HashSet<Type>(
    new[] { typeof(bool), typeof(string), typeof(Uri), typeof(byte[]), ... });

并与supportedTypes.Contains(yourType)核实。

没有魔术预定义列表与您想到的“此列表”完全匹配。例如,TypeCode没有注意到byte[]Uri


1
投票

也许是这样;如果将CLR类型定义为系统核心类型。

如果错的话,我会删除

public static class TypeExtension
{
    public static bool IsCLRType(this Type type)
    {
        var fullname = type.Assembly.FullName;
        return fullname.StartsWith("mscorlib");
    }
}

交替;

    public static bool IsCLRType(this Type type)
    {
        var definedCLRTypes = new List<Type>(){
                typeof(System.Byte),
                typeof(System.SByte),
                typeof(System.Int16),
                typeof(System.UInt16),
                typeof(System.Int32),
                typeof(System.UInt32),
                typeof(System.Int64),
                typeof(System.UInt64),
                typeof(System.Single),
                typeof(System.Double),
                typeof(System.Decimal),
                typeof(System.Guid),
                typeof(System.Type),
                typeof(System.Boolean),
                typeof(System.String),
                /* etc */
            };
        return definedCLRTypes.Contains(type);
    }

1
投票
bool isDotNetType = type.Assembly == typeof(int).Assembly;
© www.soinside.com 2019 - 2024. All rights reserved.