110,561
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public interface IClass<TEntity> where TEntity : class { }
public class Entity { }
public class ClassEntity
{
//如何知道这个Data的类型,是IClass
public IClass<Entity> Data { get; set; }
public string Str { get; set; }
}
class Program
{
static void Main(string[] args)
{
//如何判断ClassEntity中哪些属性是IClass的
var entityType = typeof(ClassEntity);
var props = entityType.GetProperties();
//下面是我自己的写法,感觉有些麻烦,不知道有没有简单的办法
foreach (var prop in props)
{
var typeArgs = prop.PropertyType.GenericTypeArguments;
if (typeArgs.Count() == 1)
{
var arg = typeArgs.Single();
var tableType = typeof(IClass<>).MakeGenericType(arg);
if (tableType.IsAssignableFrom(prop.PropertyType))
{
Console.WriteLine($"PropName={prop.Name}");
}
}
}
Console.ReadLine();
}
}
public interface IService<TEntity> where TEntity : class { }
public class BookService : IService<Book>{}
public class FileService : IService<File>{}
如何找出IService<TEntity>的继承类,我在部分DI和AOP中会用到,我自己的实现,也是和问题中差不多,将实体和接口重新组合成一个Type之后进行比对。
所以想知道,有没有可以直接比对的办法。
public interface IList<TEntity> where TEntity : class { }
public interface BaseList<TEntity> : IList<TEntity> where TEntity : class { }
public class ClassEntity
{
public BaseList<File> Data { get; set; }
public BaseList<Book> Data1 { get; set; }
public BaseList<Folder> Data2 { get; set; }
public string Str { get; set; }
}
怎么从这里面找出Data/Data1/Data2
var entityType = typeof(ClassEntity);
var props = entityType.GetProperties();
var ret = props.Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition().IsAssignableFrom(typeof(IClass<>))).ToList();
var entityType = typeof(ClassEntity);
var props = entityType.GetProperties();
var q = props.Where(x => x.PropertyType.Name.Contains("IClass"));
foreach (var p in q)
{
Console.WriteLine($"PropName={p.Name}");
}