2013-03-08 95 views
2

我想序列化一个对象,并想知道某个类型是否可以被XmlReader.ReadElementContentAsObject()ReadElementContentAs()使用。检查类型是否是一个CLR对象

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

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

你将什么定义为“CLR类型”?这不是一个具有特定单一商定含义的术语:那么,您*意味着什么? – 2013-03-08 10:29:01

+0

我想我正在寻找这个列表:http://msdn.microsoft.com/en-us/library/xa669bew.aspx – Marnix 2013-03-08 10:31:11

+0

在该链接文档中,术语“CLR类型”用于指代可以从CLR中使用,所以在这方面*您可以从CLR中访问的任何*类型是“CLR类型” – Justin 2013-03-08 10:35:08

回答

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

+0

自己制作列表不是问题,但我希望有一个更通用的解决方案。 – Marnix 2013-03-08 10:43:24

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(int32).Assembly; 
相关问题