【发布时间】:2017-04-12 20:56:41
【问题描述】:
C# 没有预处理,我不想为所有需要此约束的接口定义“struct、IComparable、IFormattable、IConvertible”。我需要的是这样的:
命名约束 "IMyItemConstraint" 用于几个通用接口 where 子句:
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 子句定义命名约束?
【问题讨论】:
-
我会为样板代码创建一个Code Snippet。另见:How to: Create a New Snippet with Replacements.
-
@TnTinMn:好主意,如果您不处于“概念”的项目阶段,您想要做出决定并且想要尝试几种变体。
-
如果您需要动态代码生成来快速评估备选方案,那么设置 T4 模板可能是值得的。请参阅:Design-Time Code Generation by using T4 Text Templates。这基本上是生成代码文件的预处理步骤。
-
谢谢! ???直到现在我才知道 4 个文本模板。寻找其他解决方案,我在这个答案中找到了 Roslyn CTP:Custom language features in C#