【问题标题】:Check if type is a CLR object检查类型是否为 CLR 对象
【发布时间】:2013-03-08 10:26:02
【问题描述】:

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

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

if(myType.IsCLRType) // how can I find this property?
    myValue = _cReader.ReadElementContentAsObject();

【问题讨论】:

  • 您将什么定义为“CLR 类型”?这不是一个具有特定单一约定含义的术语:那么 you 是什么意思?
  • 我想我正在寻找这个列表:msdn.microsoft.com/en-us/library/xa669bew.aspx
  • 在该链接文档中,术语“CLR 类型”用于指代可在 CLR 中使用的类型,因此在这方面,您可以访问的 any 类型从 CLR 内部是一个“CLR 类型”
  • 我只是在寻找当我尝试使用ReadElementContentAsObject时不会给出异常的列表。

标签: c# xmlreader


【解决方案1】:

我想我正在寻找这个列表: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

【讨论】:

  • 自己列清单不是问题,但我希望有一个更通用的解决方案。
【解决方案2】:

也许是这样;如果您将 CLR 类型定义为 System Core 类型。

如有错误我会删除

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);
    }

【讨论】:

    【解决方案3】:
    bool isDotNetType = type.Assembly == typeof(int).Assembly;
    

    【讨论】:

    • 我喜欢这个,尽管它应该是Int32int,而不是int32
    猜你喜欢
    • 2011-09-26
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2011-09-28
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多