[英]how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET
[英]How to check if type is IEnumerable<BaseType>?
應該很容易...
class Base{}
class Foo:Base{}
public bool Bar(Type t){
// return ???
// NB: shouldn't know anything about Foo, just Base
}
Assert.True(Bar(typeof(IEnumerable<Foo>));
Assert.False(Bar(typeof(IEnumerable<Base>));
Assert.False(Bar(typeof(string));
Assert.False(Bar(typeof(Foo));
只是為了回答第二個為什么應該為假的問題(實際上-沒關系,因為Bar參數永遠不會是IEnumerable<Base>
)。
我正在嘗試編寫FluentNhibernate自動映射約定,該約定將我的類枚舉映射到整數。 我已經成功地做到了,但是當我想映射IEnumerable<EnumerationChild>
(我的情況是-User.Roles),事情就失敗了。
public class EnumerationConvention:IUserTypeConvention{
private static readonly Type OpenType=typeof(EnumerationType<>);
public void Apply(IPropertyInstance instance){
//this is borked atm, must implement ienumerable case
var closedType=OpenType.MakeGenericType(instance.Property.PropertyType);
instance.CustomType(closedType);
}
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria){
criteria.Expect(
x=>typeof(Enumeration).IsAssignableFrom(x.Property.PropertyType) ||
typeof(IEnumerable<Enumeration>)
.IsAssignableFrom(x.Property.PropertyType));
}
}
您可以使用Type.IsAssignableFrom(Type)
。 但是,您的問題還不是很清楚-您要指定一種類型,但需要兩種類型…… Bar
是要檢查t
哪種類型?
請注意,由於通用協方差,答案將在.NET 3.5和.NET 4之間發生變化-例如,在.NET 3.5中, 不能將List<Foo>
分配給IEnumerable<Base>
,但是在.NET 4中可以。
編輯:這是一個打印True,True,False,False的程序。 我不確定為什么您期望第二個錯誤:
using System;
using System.Collections;
using System.Collections.Generic;
class Base{}
class Foo:Base{}
class Test
{
static bool Bar(Type t)
{
return typeof(IEnumerable<Base>).IsAssignableFrom(t);
}
static void Main()
{
Console.WriteLine(Bar(typeof(IEnumerable<Foo>)));
Console.WriteLine(Bar(typeof(IEnumerable<Base>)));
Console.WriteLine(Bar(typeof(string)));
Console.WriteLine(Bar(typeof(Foo)));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.