C# accessing a static property of type T in a generic class

前端 未结 7 1525
后悔当初
后悔当初 2020-12-16 09:30

I am trying to accomplish the following scenario that the generic TestClassWrapper will be able to access static properties of classes it is made of (they will all derive fr

7条回答
  •  被撕碎了的回忆
    2020-12-16 09:58

    T is a type, not parameter or variable so you cannot pick any value from any members. Here is a sample code.

    public class UrlRecordService
    {
        public virtual void SaveSlug(T entity) where T : ISlugSupport
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
    
            int entityId = entity.Id;
            string entityName = typeof(T).Name;
        }
    }
    
    
    public interface ISlugSupport
    {
        int Id { get; set; }
    }
    

提交回复
热议问题