public T GetExtendResult<T>(T entity) where T : IHasExtendInfo { if (entity.CreatorUserId.HasValue) { entity.CreateUserName = _userCache.Get(entity.CreatorUserId.Value).FullName; } if (entity.CancelUserId.HasValue) { entity.CancelUserName = _userCache.Get(entity.CancelUserId.Value).FullName; }if (typeof(IHasExtendAheadInfo).IsAssignableFrom(typeof(T))) { if (((IHasExtendAheadInfo)entity).AheadUserId.HasValue) { ((IHasExtendAheadInfo)entity).AheadUserName = _userCache.Get(((IHasExtendAheadInfo)entity).AheadUserId.Value).FullName; } } if (typeof(IHasExtendOpenInfo).IsAssignableFrom(typeof(T))) { if (((IHasExtendOpenInfo)entity).OpenUserId.HasValue) { ((IHasExtendOpenInfo)entity).OpenUserName = _userCache.Get(((IHasExtendOpenInfo)entity).OpenUserId.Value).FullName; } }return entity; }
public class Dog : Animal { public string name { get; set; } } public class Animal { public string id { get; set; } } public class Main { public void Main() { Dog aa = new Dog { name = "狗", id = "动物" }; CheckClass(aa); } public void CheckClass<T>(T entity) { bool re1 = typeof(Animal).IsAssignableFrom(typeof(T)); //返回true的条件是Dog类直接或间接的实现了Animal类; bool re2 = typeof(T).IsSubclassOf(typeof(Animal)); //返回true的条件是Dog类是Animal的子类 var id = (entity as Animal).id; } }