2013-03-08 101 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; 
相關問題