generic NOT constraint where T : !IEnumerable

前端 未结 7 1447
余生分开走
余生分开走 2020-12-03 13:31

As per the title, is it possible to declare type-negating constraints in c# 4 ?

7条回答
  •  Happy的楠姐
    2020-12-03 13:58

    As far as I know a Not contraint is not possible. You CAN use base classes and/or Interfaces to constrain a Generic. Faced with a similar problem leading to runtime failures, I implemented an interface on the classes the Generic was to handle:

    public interface IOperations
    {
    
    }
    
    public static T GenericOperationsFactory(ILogger loggerInstance, ref ExecutionContext executionContext) 
            where T: IOperations
    {
        var operationsContext = Factories.OperationsContextFactory(loggerInstance, ref executionContext);
    
        var operations = typeof(T).GetConstructor(new[] { typeof(OperationsContext) }).Invoke(new object[] { operationsContext });
    
        return (T)operations;
    }
    
    public abstract class OperationsBase:IOperations
    {
        protected OperationsContext Context { get; set; }
    
        public OperationsBase(OperationsContext context)
        {
            Context = context;
        }
    ...
    
    public class ListsOperations : OperationsBase
    {
        public ListsOperations(OperationsContext context) :
            base(context)
        {
    
        }
    

    alternatively:

    public static T GenericOperationsFactory(ILogger loggerInstance, ref ExecutionContext executionContext) 
            where T: OperationsBase
    {
        var operationsContext = Factories.OperationsContextFactory(loggerInstance, ref executionContext);
    
        var operations = typeof(T).GetConstructor(new[] { typeof(OperationsContext) }).Invoke(new object[] { operationsContext });
    
        return (T)operations;
    }
    
    public abstract class OperationsBase
    {
        protected OperationsContext Context { get; set; }
    
        public OperationsBase(OperationsContext context)
        {
            Context = context;
        }
    ...
    
    public class ListsOperations : OperationsBase
    {
        public ListsOperations(OperationsContext context) :
            base(context)
        {
    
        }
    

提交回复
热议问题