C# 无法获取通过引用传递参数的正确数据类型
我需要帮助,我一直收到一个错误。。。此部分中有一些无效参数:C# 无法获取通过引用传递参数的正确数据类型,c#,ienumerable,observablecollection,C#,Ienumerable,Observablecollection,我需要帮助,我一直收到一个错误。。。此部分中有一些无效参数: this.Search(ref objResult, sSQL); 我无法将收藏作为参考传递 internal override Models.BaseCollectionModel<Models.CategoryModel> OnFind(string objQueryArgs) { Models.Collection.CategoryCollectionModel objResult = new Mode
this.Search(ref objResult, sSQL);
我无法将收藏作为参考传递
internal override Models.BaseCollectionModel<Models.CategoryModel> OnFind(string objQueryArgs)
{
Models.Collection.CategoryCollectionModel objResult = new Models.Collection.CategoryCollectionModel();
string sSQL = string.Empty;
sSQL = "SELECT * FROM " + this.TableName;
this.Search(ref objResult, sSQL);
return objResult;
}
internal virtual void Search(ref System.Collections.IEnumerable objResult, string sQuery)
{
//statement goes here...
}
只是从中继承的附加信息CategoryCollectionModel
Models.BaseCollectionModel
它还继承System.Collections.ObjectModel.ObservableCollection根据方法声明,将objResult的类型设置为IEnumerable:
System.Collections.IEnumerable objResult =
^------+----------^
|
+- with the right using directives, this part is redundant
ref参数必须与声明匹配,它不能与赋值兼容,它必须是精确的声明
原因是该方法可以将该变量的内容交换为同一类型的不同值,但这不能保证是CategoryCollectionModel
这里有一个控制问题:你真的需要ref吗
为什么有ref参数?是因为您想要对集合的引用,而不是集合的副本吗?或者您真的打算将集合切换到完全不同的集合吗?请注意,列表是一种引用类型。这意味着该值是通过引用传递的。
从调用的方法内部操纵值或内容也会更改源对象。这是引用类型的默认行为
记住使用ref或out方法签名必须匹配:参数必须与传递的对象完全相同。这是内存分配的必要条件。假设List和IEnumerable可以替代访问IEnumerable对象级别上的List,但由于类型不同,它们在不同位置分配的内存量不同。它们在内存中的帧不相同,因此指针将变得无效。
因此,在使用ref或使用指针对非托管对象进行编码时,请注意类型
当默认行为发生时,原始列表和副本列表都指向相同的值
传递引用类型:
List<int> originalList = new List<int>();
originalList.add(1);
AddMore(originalList);
private void AddMore(List<int> list)
{
// OriginalList will now also contain two objects (Count = 2)
// Both lists are sharing the same reference and therefore are pointing
// to the same memory location
list.Add(2);
// Create a new reference for variable of type List<int>.
// This will override list but not originalList
// originalList.Count is still 2!
list = new List<int>();
// originalList still has two objects. Not three!
// The local variable is now pointing to a new/ different memomory location
// than originalList is pointing to
list.Add(3)
}
我正在使用ref,这样CategoryCollectionModel将包含我试图获取的序列化数据。
private void AddMore(ref List<int> list)
{
// OriginalList will now also contain two objects (Count = 2)
// Both (original and copy) are pointing to the same values since the variables
// are now equal
list.Add(2);
// This creates a new reference for BOTH variables!
// originalList.Count is now 0
list = new List<int>();
// Both list's count is now 1!
list.Add(3);
}