影响作为参数传递给方法的ICollection
本文关键字:方法 ICollection 参数传递 影响 | 更新日期: 2023-09-27 18:29:11
我有一个类,它有一个ICollection
属性,该属性是构造函数在实例化该类时指定的,但我想将该属性绑定到原始集合,以便在更新/更改它时,原始列表也是如此。做这件事的最佳方法是什么?
这里有一个例子:
public class Organizations
{
private ICollection<Organization> _orgs;
public Organizations(ICollection<Organization> orgs)
{
_orgs = orgs;
}
public void TestAdd()
{
_orgs.Add(new Organization {Name = "Testing 123"});
}
}
// in another class
public ActionResult TestApi()
{
var tmp = new SyncTool.Core.Extensions.Zendesk.Organizations(ZendeskCache.Organizations.Data);
var zd = ZendeskCache.Organizations.Data.FirstOrDefault(n => n.Name.Contains("Testing 123"));
//ZendeskCache.Org.... is a List<Organization>
return Json(new {data = "tmp" }, AG);
}
List<Organization>
是一个引用对象。这段代码按照你想要的方式工作(除了语法错误),你试过了吗?
复制更简单:
public class Program
{
public static void Main(string[] args)
{
var orgs = new List<string>();
var orgClass = new Organizations(orgs);
orgClass.TestAdd();
Console.WriteLine(orgs.First());
Console.Read();
}
}
public class Organizations
{
private ICollection<string> _orgs;
public Organizations(ICollection<string> orgs)
{
_orgs = orgs;
}
public void TestAdd()
{
_orgs.Add("Testing 123");
}
}
//Output: "Testing 123"