我有一个表示范围列表的对象。我按如下方式实现它:
public class SelectiveOutputRangeCollection<T> : ObservableCollection<SelectiveOutputRange<T>> {
public bool CanAdd() {
return (this.Count < SelectiveOutputWindow.MaxNumberOfRanges);
}
}
public class SelectiveOutputRange<T> : Tuple<T, T> {
public override string ToString() {
return this.Item1 + " to " + this.Item2;
}
}
这不会编译:
“System.Tuple
即使添加一个简单的无参数构造函数也会导致相同的错误出现两次。现在我想起了 Item1
和 Item2
是官方只读的(因为构造 Tuple
的首选方法是通过 Tuple.Create<T, T>()
)。
public class SelectiveOutputRange<T> : Tuple<T, T> { // <-- error here
public SelectiveOutputRange() { // <-- error here
this.Item1 = default(T); // <-- field is read only
this.Item2 = default(T); // <-- field is read only
}
public override string ToString() {
return this.Item1 + " to " + this.Item2;
}
}
我知道 WPF 对无参数构造函数很感兴趣,所以我认为这是因为 ObservableCollection
引起的希望能够初始化它的 Tuple<T, T>
s 但它不能。
我不需要 Tuple<T, T>
的那么多类(class);我知道我可以只添加两个 T
类型的字段到 SelectiveOutputRange<T>
上课,收工。
但是为了我的好奇,有没有办法使用Tuple
WPF 中的 s ObservableCollection
?还是这里发生了其他奇怪的事情?
最佳答案
自 Tuple<,>
是不可变的,你需要添加一个构造函数,让你用有意义的数据初始化它:
public SelectiveOutputRange(T a, T b) : base(a, b) {
}
如果没有这样的构造函数,您的 Tuple
结构将无法使用。
如果你想要你的 Tuple
要可修改,在这种情况下您应该更喜欢包含:
class SelectiveOutputRange<T> {
public Tuple<T,T> Range {get;private set;}
}
如果您想制作 SelectiveOutputRange<T>
可用的地方 Tuple<T,T>
是必需的,向类添加隐式转换运算符,返回 Range
SelectiveOutputRange
中包含的属性对象。
关于c# - 从其子类初始化 C# Tuple<T, T> 以便在 WPF 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18921504/