我正在尝试序列化某个对象,并想知道XmlReader.ReadElementContentAsObject()
或ReadElementContentAs()
是否可以使用某种类型。
我可以询问一个类型是否是CLR类型,所以我知道我可以将它传递给这些方法吗?
if(myType.IsCLRType) // how can I find this property?
myValue = _cReader.ReadElementContentAsObject();
答案 0 :(得分: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 :(得分: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);
}
答案 2 :(得分:1)
bool isDotNetType = type.Assembly == typeof(int).Assembly;