问题描述
我收到以下错误 “组合的左侧必须是变量,属性或索引器” 在此代码中:
class SomeClass{
string SomeString {get; set;}
}
ObservableCollection<SomeClass> someCollection;
void foo(SomeClass foo2,string y){
someCollection.First(x => x.someString == y) = foo2;
}
我了解为什么会发生此错误,因此我编写了以下代码来解决该问题:
class SomeClass{
string SomeString {get; set;}
}
ObservableCollection<SomeClass> someCollection;
void foo(SomeClass foo2,string y){
someCollection[someCollection.IndexOf(someCollection.First(x => x.someString == y))] = foo2;
}
解决方法
我建议创建一些扩展方法以扩展ObservableCollection
以获得新功能:
public static class ObservableCollectionExt {
public static int IndexOf<T>(this ObservableCollection<T> aCollection,Func<T,bool> predFn) => aCollection.Select((c,n) => new { c,n }).FirstOrDefault(cn => predFn(cn.c))?.n ?? -1;
public static void SetFirstItem<T>(this ObservableCollection<T> aCollection,bool> predFn,T newItem) {
var index = aCollection.IndexOf(predFn);
if (index != -1)
aCollection[index] = newItem;
}
}
然后您可以在foo
中使用它们:
void foo(SomeClass foo2,string y) {
someCollection.SetFirstItem(x => x.SomeString == y,foo2);
}
,
左侧仍然不是变量。
class SomeClass{
string SomeString {get; set;}
}
ObservableCollection<SomeClass> someCollection;
void foo(string y){
var foo2 = someCollection[someCollection.IndexOf(someCollection.First(x => x.SomeString == y))] ;
}