无法通过引用获取正确的数据类型来传递参数

时间:2014-03-10 08:38:54

标签: c# ienumerable observablecollection

我在这里需要帮助,我在这部分中一直收到错误 ...有一些无效的参数

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<Models.CategoryModel> 它也继承了System.Collections.ObjectModel.ObservableCollection<T>

2 个答案:

答案 0 :(得分:0)

根据方法声明为<{1}} objResult设置类型:

IEnumerable

System.Collections.IEnumerable objResult = ^------+----------^ | +- with the right using directives, this part is redundant 参数必须与声明匹配,它不能与赋值兼容,它必须是那个确切的声明。

原因是该方法可以将该变量的内容替换为相同类型的不同值,但不能保证为CategoryCollectionModel。

以下是控制问题:您真的需要ref吗?

为什么你有一个ref参数?是因为您想要对集合的引用,而不是集合的副本?或者你真的打算把这个系列改成一个完全不同的系列吗?

答案 1 :(得分:0)

请注意,List是引用类型。这意味着它(值)通过引用传递。 操作调用方法内部的值或内容也将更改源对象。这是引用类型的默认行为。

请记住使用ref或out方法签名必须匹配:params必须与传递的对象完全相同。这对于内存分配来说是非常必要的。假设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)
}

如果所需的行为是originalList变量也应该指向一个新的引用(相同!)而不是ref将完成这项工作。 list和originalList是相等的对象(相同的引用):

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);
}