要检查类型是否是C#中另一种类型的子类,很容易:
typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true
Run Code Online (Sandbox Code Playgroud)
但是,这将失败:
typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false
Run Code Online (Sandbox Code Playgroud)
有没有办法检查类型是否是基类本身的子类OR,而不使用OR运算符或使用扩展方法?
在这个链接上,在备注部分提到了" TypeNameHandling".在什么情况下,如果使用序列化/反序列化来自外部源的JSON会有害SerializationBinder?一个工作的例子将不胜感激.
我的类DataType有一个JsonConverter.当Json中使用的普通字符串作为DataType类型的属性值时,我想做一些特殊处理.在值是"完整"对象的情况下,我想进行"正常"反序列化.
这是我的尝试
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value != null && reader.ValueType == typeof (string))
{
return someSpecialDataTypeInstance;
}
else if (reader.TokenType == JsonToken.StartObject)
{
DataType dataType = serializer.Deserialize<DataType>(reader);
return dataType;
}
else
{
throw new JsonSerializationException();
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为这一行:DataType dataType = serializer.Deserialize(reader); 导致无限递归.
这可以轻易地完成吗?(无需手动逐个财产)
这是我从 Web 服务获得的 JSON 响应:
{
"odata.metadata": "https://graph.windows.net/00c6cd14-eaee-4d02-9807-59bcd4f98847/$metadata#domainDnsRecords",
"value": [{
"odata.type": "Microsoft.DirectoryServices.DomainDnsTxtRecord",
"dnsRecordId": "aceff52c-06a5-447f-ac5f-256ad243cc5c",
"isOptional": false,
"label": "aro3652698.applabdnstest1.com",
"recordType": "Txt",
"supportedService": "Email",
"ttl": 3600,
"text": "MS=ms14815229"
},
{
"odata.type": "Microsoft.DirectoryServices.DomainDnsMxRecord",
"dnsRecordId": "5fbde38c-0865-497f-82b1-126f596bcee9",
"isOptional": false,
"label": "aro3652698.applabdnstest1.com",
"recordType": "Mx",
"supportedService": "Email",
"ttl": 3600,
"mailExchange": "ms14815229.msv1.invalid",
"preference": 32767
}]
}
Run Code Online (Sandbox Code Playgroud)
“value”标记下数组中的元素具有不同的派生类型。
有DomainDnsRecord抽象基类,从基类继承的类是DomainDnsTxtRecord和DomainDnsMxRecord。
在给定的 JSON 数组中(但不总是!),第一个元素是 of DomainDnsTxtRecord,第二个元素是DomainDnsMxRecord类型。
包含有关给定元素是什么类型的信息的字段是:“recordType”。
将此 JSON 数组反序列化为基类列表的最简单、最方便的方法是什么,例如List<DomainDnsRecord>(例如(使用 Newtonsoft))?
这是一个非常普遍的问题,但我正在做的具体事情很简单,所以我要包含代码.当我在编译时不知道两种对象的类型时,如何检查两个对象之间的类型兼容性?
也就是说,我可以做的if (object is SomeType)时候SomeType是在编译时已知的类型名称.GetType()是不够的,因为它不适用于派生类型.基本上我想能够说,if (object.IsTypeOfOrIsDerivedFrom(someType))这个神奇方法的签名是什么IsTypeOfOrIsDerivedFrom(Type type)
这是上下文.
// Return all controls that are (or are derived from) any of a list of Types
public static IEnumerable<Control> FindControls(this Control control, IEnumerable<Type> types, bool recurse)
{
foreach (Control ctl in control.Controls)
{
/// How can I compare the base types of item & ctl?
if (types.Any(item=> .... ))
{
yield return (ctl);
}
if (recurse && ctl.Controls.Count > 0)
{
IEnumerable<Control> subCtl …Run Code Online (Sandbox Code Playgroud)