如何为通用接口 where 子句定义约束

How to define constraint for generic interface where-clause

C# 没有预处理,我不想为所有需要此约束的接口定义 "struct, IComparable, IFormattable, IConvertible"。我需要的是:

几个通用接口 where-clauses 的命名约束 "IMyItemConstraint":

public interface IProperty2Enum<T>
    : IEnumerable<T>
    where T : IMyItemConstraint { } // <--- here

public interface IMyCollection2<T>
    : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged 
    where T : IMyItemConstraint { } // <--- here

public interface IMyObservableCollection2<T>
    : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged 
    where T : IMyItemConstraint { } // <--- here

我试图定义一个名称 "IMyItemConstraint",但出现错误 CS####:

public interface IMyItemConstraint 
    : struct, IComparable, IFormattable, IConvertible { } // CS1031: Type expected 

public interface IMyItemConstraint : where IMyItemConstraint
    : struct, IComparable, IFormattable, IConvertible { } // CS1031: Type expected 

public interface IMyItemConstraint<T> where T // This does not help:
    : struct, IComparable, IFormattable, IConvertible { }

是否可以为多个接口(合同)的通用接口 where-clause 定义命名约束?

遗憾的是,您无法继承通用约束。您需要为每个类型参数单独定义约束。